Skip to content

Commit ed4403a

Browse files
committed
Add benchmark script before vs after ClassReflection script
1 parent cfdf0fa commit ed4403a

1 file changed

Lines changed: 131 additions & 0 deletions

File tree

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Benchmark for refreshing the scope of a changed class node (ChangedNodeScopeRefresher::refresh()).
7+
*
8+
* When a rule changes a class-like node, its stmts are re-processed with the in-class scope. That
9+
* scope held the class reflection of the original file, so rules deciding on reflection (e.g. "has
10+
* this trait already?") did not see their own change and re-applied it on every pass.
11+
*
12+
* The change (#8728) rebuilds the class reflection from the changed class node via BetterReflection
13+
* NodeToReflection + ClassReflectionFactory (AstClassReflectionFactory) and re-enters the class with
14+
* it, under a fresh cache key so member caches of the former reflection are not reused.
15+
*
16+
* This bench parses a file of many classes (parent, interface, constants, properties, methods),
17+
* attaches scope (as the real run does), then drives refresh() over every class node - the exact
18+
* path RectorRunner takes after a rule returns a changed Class_.
19+
*
20+
* Run on both branches to compare:
21+
* php bench/class_reflection_refresh_bench.php
22+
*
23+
* Reports CPU time (user+sys) and wall time; CPU is the reliable metric, wall is noisy under
24+
* concurrent load.
25+
*/
26+
27+
use PhpParser\Node\Stmt\Class_;
28+
use PHPStan\Analyser\MutatingScope;
29+
use Rector\Application\ChangedNodeScopeRefresher;
30+
use Rector\DependencyInjection\LazyContainerFactory;
31+
use Rector\NodeTypeResolver\Node\AttributeKey;
32+
use Rector\PhpParser\Node\BetterNodeFinder;
33+
use Rector\Testing\TestingParser\TestingParser;
34+
35+
require __DIR__ . '/../vendor/autoload.php';
36+
37+
const CLASSES = 40; // classes in the parsed file
38+
const METHODS = 10; // methods per class
39+
const REPEAT = 20; // outer repeats over the whole set
40+
41+
$rectorConfig = (new LazyContainerFactory())->create();
42+
$rectorConfig->boot();
43+
44+
/** @var TestingParser $testingParser */
45+
$testingParser = $rectorConfig->make(TestingParser::class);
46+
47+
/** @var BetterNodeFinder $betterNodeFinder */
48+
$betterNodeFinder = $rectorConfig->make(BetterNodeFinder::class);
49+
50+
/** @var ChangedNodeScopeRefresher $changedNodeScopeRefresher */
51+
$changedNodeScopeRefresher = $rectorConfig->make(ChangedNodeScopeRefresher::class);
52+
53+
$source = "<?php\n\ndeclare(strict_types=1);\n\nnamespace Bench;\n\n";
54+
$source .= "interface SomeContract\n{\n public function handle(int \$value): int;\n}\n\n";
55+
$source .= "abstract class SomeParent\n{\n protected array \$items = [];\n\n";
56+
$source .= " public function parentMethod(string \$name): string\n {\n return strtoupper(\$name);\n }\n}\n\n";
57+
58+
for ($i = 0; $i < CLASSES; ++$i) {
59+
$source .= "final class Service{$i} extends SomeParent implements SomeContract\n{\n";
60+
$source .= " public const NAME = 'service{$i}';\n\n";
61+
$source .= " private int \$counter = 0;\n\n";
62+
$source .= " private ?\\DateTimeImmutable \$createdAt = null;\n\n";
63+
$source .= " public function handle(int \$value): int\n {\n return \$this->counter += \$value;\n }\n\n";
64+
65+
for ($j = 0; $j < METHODS; ++$j) {
66+
$source .= " public function method{$j}(string \$name): string\n {\n";
67+
$source .= " \$this->items[] = \$name;\n";
68+
$source .= " return \$this->parentMethod(\$name) . self::NAME . \$this->handle({$j});\n }\n\n";
69+
}
70+
71+
$source .= "}\n\n";
72+
}
73+
74+
$sourceFilePath = tempnam(sys_get_temp_dir(), 'bench_') . '.php';
75+
file_put_contents($sourceFilePath, $source);
76+
77+
$stmts = $testingParser->parseFileToDecoratedNodes($sourceFilePath);
78+
79+
/** @var Class_[] $classes */
80+
$classes = array_values(array_filter(
81+
$betterNodeFinder->findInstanceOf($stmts, Class_::class),
82+
static fn (Class_ $class): bool => $class->isFinal()
83+
));
84+
85+
// keep the original in-class scope, as RectorRunner passes the scope of the node before the change
86+
$scopes = [];
87+
foreach ($classes as $key => $class) {
88+
$scope = $class->getAttribute(AttributeKey::SCOPE);
89+
if (! $scope instanceof MutatingScope || ! $scope->isInClass()) {
90+
fwrite(STDERR, 'Class node is missing the in-class scope, bench would not hit the refresh path' . PHP_EOL);
91+
exit(1);
92+
}
93+
94+
$scopes[$key] = $scope;
95+
}
96+
97+
$cpuSeconds = static function (): float {
98+
$usage = getrusage();
99+
return $usage['ru_utime.tv_sec'] + $usage['ru_utime.tv_usec'] / 1_000_000
100+
+ $usage['ru_stime.tv_sec'] + $usage['ru_stime.tv_usec'] / 1_000_000;
101+
};
102+
103+
$run = static function () use ($changedNodeScopeRefresher, $classes, $scopes, $sourceFilePath): void {
104+
foreach ($classes as $key => $class) {
105+
$changedNodeScopeRefresher->refresh($class, $sourceFilePath, $scopes[$key]);
106+
}
107+
};
108+
109+
// warm up autoloading/reflection caches once, excluded from timing
110+
$run();
111+
112+
$memoryStart = memory_get_usage();
113+
$wallStart = microtime(true);
114+
$cpuStart = $cpuSeconds();
115+
116+
for ($repeat = 0; $repeat < REPEAT; ++$repeat) {
117+
$run();
118+
}
119+
120+
$cpu = $cpuSeconds() - $cpuStart;
121+
$wall = microtime(true) - $wallStart;
122+
$memory = memory_get_usage() - $memoryStart;
123+
124+
@unlink($sourceFilePath);
125+
126+
$totalCalls = REPEAT * count($classes);
127+
128+
printf('classes: %d, methods/class: %d, repeats: %d, refresh() calls: %d%s', count($classes), METHODS + 1, REPEAT, $totalCalls, PHP_EOL);
129+
printf('CPU: %.4f s (%.3f us/call)%s', $cpu, $cpu / $totalCalls * 1_000_000, PHP_EOL);
130+
printf('wall: %.4f s%s', $wall, PHP_EOL);
131+
printf('memory growth: %.2f MB%s', $memory / 1024 / 1024, PHP_EOL);

0 commit comments

Comments
 (0)