Skip to content

Commit e0f59a8

Browse files
perf: Optimize class reflection refresh with cheaper cache hashing and early class-name validation (#8892)
* perf: Optimize class reflection refresh with cheaper cache hashing and early class-name validation * [ci-review] Rector Rectify * add script * clean up --------- Co-authored-by: GitHub Action <actions@github.com>
1 parent 25d54e8 commit e0f59a8

3 files changed

Lines changed: 76 additions & 7 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Benchmark cached AstClassReflectionFactory::create() calls, including printing and hashing.
7+
* Parsing, container setup, and the initial reflection build are excluded from timing.
8+
* This does not measure ChangedNodeScopeRefresher::refresh() or total Rector runtime.
9+
*
10+
* The container injects the printer used by the factory on the current branch.
11+
* PHPStanNodeScopeResolver.php supplies a large class as benchmark input.
12+
*
13+
* Run on both branches with the same input file to compare:
14+
* php bench/ast_class_reflection_factory_bench.php
15+
*/
16+
17+
use PhpParser\Node\Stmt\Class_;
18+
use PhpParser\NodeFinder;
19+
use PhpParser\NodeTraverser;
20+
use PhpParser\NodeVisitor\NameResolver;
21+
use PhpParser\ParserFactory;
22+
use Rector\DependencyInjection\LazyContainerFactory;
23+
use Rector\NodeTypeResolver\PHPStan\Scope\AstClassReflectionFactory;
24+
use Rector\NodeTypeResolver\PHPStan\Scope\ScopeFactory;
25+
26+
require __DIR__ . '/../tests/bootstrap.php';
27+
28+
const RUNS = 3;
29+
const LOOKUPS = 1000;
30+
31+
$rectorConfig = (new LazyContainerFactory())->create();
32+
$rectorConfig->boot();
33+
34+
$astClassReflectionFactory = $rectorConfig->make(AstClassReflectionFactory::class);
35+
$inputFilePath = __DIR__ . '/../src/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php';
36+
$inputSource = file_get_contents($inputFilePath);
37+
if ($inputSource === false) {
38+
throw new RuntimeException('Cannot read benchmark input: ' . $inputFilePath);
39+
}
40+
41+
$nodes = (new ParserFactory())->createForNewestSupportedVersion()->parse($inputSource);
42+
$nodes = (new NodeTraverser(new NameResolver()))->traverse($nodes ?? []);
43+
$inputClass = (new NodeFinder())->findFirstInstanceOf($nodes, Class_::class);
44+
if (! $inputClass instanceof Class_) {
45+
throw new RuntimeException('Benchmark input must contain a class.');
46+
}
47+
48+
$scope = $rectorConfig->make(ScopeFactory::class)
49+
->createFromFile($inputFilePath)
50+
->enterNamespace('Rector\\NodeTypeResolver\\PHPStan\\Scope');
51+
52+
// Warm the reflection cache before measuring repeated lookups.
53+
$astClassReflectionFactory->create($inputClass, $scope);
54+
55+
$totalMilliseconds = 0.0;
56+
for ($run = 1; $run <= RUNS; ++$run) {
57+
$start = hrtime(true);
58+
for ($i = 0; $i < LOOKUPS; ++$i) {
59+
$astClassReflectionFactory->create($inputClass, $scope);
60+
}
61+
62+
$milliseconds = (hrtime(true) - $start) / 1e6;
63+
$totalMilliseconds += $milliseconds;
64+
printf("Run %d: %d cached lookups: %.1f ms\n", $run, LOOKUPS, $milliseconds);
65+
}
66+
67+
printf("Average: %.1f ms\n", $totalMilliseconds / RUNS);

‎src/Application/ChangedNodeScopeRefresher.php‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,14 @@ private function refreshClassReflection(ClassLike $classLike, MutatingScope $mut
116116
return $mutatingScope;
117117
}
118118

119-
$classReflection = $this->astClassReflectionFactory->create($classLike, $mutatingScope);
120-
if (! $classReflection instanceof ClassReflection) {
119+
$currentClassReflection = $mutatingScope->getClassReflection();
120+
$className = (string) ($classLike->namespacedName ?? $classLike->name);
121+
if (! $currentClassReflection instanceof ClassReflection || $currentClassReflection->getName() !== $className) {
121122
return $mutatingScope;
122123
}
123124

124-
$currentClassReflection = $mutatingScope->getClassReflection();
125-
if (! $currentClassReflection instanceof ClassReflection || $currentClassReflection->getName() !== $classReflection->getName()) {
125+
$classReflection = $this->astClassReflectionFactory->create($classLike, $mutatingScope);
126+
if (! $classReflection instanceof ClassReflection) {
126127
return $mutatingScope;
127128
}
128129

‎src/NodeTypeResolver/PHPStan/Scope/AstClassReflectionFactory.php‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PhpParser\Node\Stmt\Enum_;
1010
use PhpParser\Node\Stmt\Interface_;
1111
use PhpParser\Node\Stmt\Namespace_;
12+
use PhpParser\PrettyPrinter\Standard;
1213
use PHPStan\Analyser\MutatingScope;
1314
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass as ReflectionClassAdapter;
1415
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum as ReflectionEnumAdapter;
@@ -19,7 +20,6 @@
1920
use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
2021
use PHPStan\Reflection\ClassReflection;
2122
use PHPStan\Reflection\ClassReflectionFactory;
22-
use Rector\PhpParser\Printer\BetterStandardPrinter;
2323

2424
/**
2525
* The class reflection from the reflection provider is built from the original file,
@@ -39,7 +39,7 @@ final class AstClassReflectionFactory
3939
public function __construct(
4040
private readonly Reflector $reflector,
4141
private readonly ClassReflectionFactory $classReflectionFactory,
42-
private readonly BetterStandardPrinter $betterStandardPrinter,
42+
private readonly Standard $standardPrinter,
4343
) {
4444
}
4545

@@ -51,7 +51,8 @@ public function create(Class_|Interface_|Enum_ $classLike, MutatingScope $mutati
5151
// the class node is refreshed on every change in it, while its members often stay the same between passes;
5252
// reuse the reflection built from the same content, so its cache key and member caches are not created again
5353
$classKey = $filePath . ':' . $namespace . '\\' . $classLike->name;
54-
$contentHash = hash('xxh128', $this->betterStandardPrinter->print($classLike));
54+
// Hashing needs deterministic content, without Rector's output formatting and AST adjustments.
55+
$contentHash = hash('xxh128', $this->standardPrinter->prettyPrint([$classLike]));
5556

5657
if (isset($this->classReflectionsByClass[$classKey]) && $this->classReflectionsByClass[$classKey][0] === $contentHash) {
5758
return $this->classReflectionsByClass[$classKey][1];

0 commit comments

Comments
 (0)