Skip to content

Conversation

@TomasVotruba
Copy link
Member

@TomasVotruba TomasVotruba commented Nov 19, 2025

I was wonder whether this is the fastest way to mach a $node object against getNodeTypes() string node-class types.
As we do now in RectorNodeTraverser:

/**
     * @return NodeVisitor[]
     */
    public function getVisitorsForNode(Node $node): array
    {
        $nodeClass = $node::class;

        if (! isset($this->visitorsPerNodeClass[$nodeClass])) {
            $this->visitorsPerNodeClass[$nodeClass] = [];
            /** @var RectorInterface $visitor */
            foreach ($this->visitors as $visitor) {
                foreach ($visitor->getNodeTypes() as $nodeType) {
                    if (is_a($nodeClass, $nodeType, true)) {
                        $this->visitorsPerNodeClass[$nodeClass][] = $visitor;
                        continue 2;
                    }
                }
            }
        }

        return $this->visitorsPerNodeClass[$nodeClass];
    }

Alternative approach - constant map

  • has a node class map that checks instance mapping e.g. FunctionLike::class => [ClassMethod::class, Function_::class]... and in_array()

I'm dumping the script here, so we know how it performs, and have comparison for the future. + For anyone who might be interasted in real numbers :)


Run

php scripts/bench/node-lookup-vs-instanceof.php

Results

Traversals per run: 10000
Runs: 10

Average time per traversed file (nanoseconds):
Static table:           9821.06816 ns
is_a() check:           8219.7443 ns

Ratio (table / is_a): 1.1948143155743

Ignore sink: 0

The is_a() is still fastest way to check node type, by ~20 % ✔️

@TomasVotruba TomasVotruba changed the title tv perf node static map vs is a [performance test] node static map vs is_a() check of node type Nov 19, 2025
@TomasVotruba TomasVotruba changed the title [performance test] node static map vs is_a() check of node type [performance-test] node static map vs is_a() check of node type Nov 19, 2025
@TomasVotruba TomasVotruba force-pushed the tv-perf-node-static-map-vs-is-a branch from 11d3d83 to 14c1ea3 Compare November 19, 2025 10:15
@TomasVotruba
Copy link
Member Author

cc @staabm Hi Markus, I'm ccing you here in case you'd be working on php-parser related optimizations :)
I'm testing various experiment to see what is the bottleneck when it comes to node instances and traversing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants