Skip to content

Commit ddc08ce

Browse files
committed
[perf] Reuse rebuilt ClassReflection by class content hash to stop memory growth on class refresh
1 parent ed4403a commit ddc08ce

7 files changed

Lines changed: 181 additions & 7 deletions

File tree

‎bench/class_reflection_refresh_bench.php‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,22 @@
1717
* attaches scope (as the real run does), then drives refresh() over every class node - the exact
1818
* path RectorRunner takes after a rule returns a changed Class_.
1919
*
20+
* By default the classes are refreshed with the same content on every pass, as when a rule keeps
21+
* visiting a class it does not change further. With "changed", every refresh toggles an extra
22+
* constant first, so each refresh sees a class content different from the former one.
23+
*
2024
* Run on both branches to compare:
2125
* php bench/class_reflection_refresh_bench.php
26+
* php bench/class_reflection_refresh_bench.php changed
2227
*
2328
* Reports CPU time (user+sys) and wall time; CPU is the reliable metric, wall is noisy under
2429
* concurrent load.
2530
*/
2631

32+
use PhpParser\Node\Const_;
33+
use PhpParser\Node\Scalar\Int_;
2734
use PhpParser\Node\Stmt\Class_;
35+
use PhpParser\Node\Stmt\ClassConst;
2836
use PHPStan\Analyser\MutatingScope;
2937
use Rector\Application\ChangedNodeScopeRefresher;
3038
use Rector\DependencyInjection\LazyContainerFactory;
@@ -38,6 +46,8 @@
3846
const METHODS = 10; // methods per class
3947
const REPEAT = 20; // outer repeats over the whole set
4048

49+
$isChanged = ($argv[1] ?? '') === 'changed';
50+
4151
$rectorConfig = (new LazyContainerFactory())->create();
4252
$rectorConfig->boot();
4353

@@ -100,8 +110,21 @@
100110
+ $usage['ru_stime.tv_sec'] + $usage['ru_stime.tv_usec'] / 1_000_000;
101111
};
102112

103-
$run = static function () use ($changedNodeScopeRefresher, $classes, $scopes, $sourceFilePath): void {
113+
$run = static function () use ($changedNodeScopeRefresher, $classes, $scopes, $sourceFilePath, $isChanged): void {
104114
foreach ($classes as $key => $class) {
115+
if ($isChanged) {
116+
if ($class->stmts[0] instanceof ClassConst && $class->stmts[0]->consts[0]->name->toString() === 'EXTRA') {
117+
array_shift($class->stmts);
118+
} else {
119+
// BetterReflection asserts the constant lines, so mirror the class lines as rules do for new nodes
120+
$lines = [
121+
'startLine' => $class->getStartLine(),
122+
'endLine' => $class->getStartLine(),
123+
];
124+
array_unshift($class->stmts, new ClassConst([new Const_('EXTRA', new Int_(1), $lines)], 0, $lines));
125+
}
126+
}
127+
105128
$changedNodeScopeRefresher->refresh($class, $sourceFilePath, $scopes[$key]);
106129
}
107130
};
@@ -125,6 +148,7 @@
125148

126149
$totalCalls = REPEAT * count($classes);
127150

151+
printf('mode: %s%s', $isChanged ? 'changed' : 'same', PHP_EOL);
128152
printf('classes: %d, methods/class: %d, repeats: %d, refresh() calls: %d%s', count($classes), METHODS + 1, REPEAT, $totalCalls, PHP_EOL);
129153
printf('CPU: %.4f s (%.3f us/call)%s', $cpu, $cpu / $totalCalls * 1_000_000, PHP_EOL);
130154
printf('wall: %.4f s%s', $wall, PHP_EOL);

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

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,27 @@
1919
use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
2020
use PHPStan\Reflection\ClassReflection;
2121
use PHPStan\Reflection\ClassReflectionFactory;
22+
use Rector\PhpParser\Printer\BetterStandardPrinter;
2223

2324
/**
2425
* The class reflection from the reflection provider is built from the original file,
2526
* so it does not know about members a rule added or removed; build it from the current class node instead
2627
*
2728
* @see \PHPStan\Analyser\StmtHandler\ClassLikeHandler::createAstClassReflection()
2829
*/
29-
final readonly class AstClassReflectionFactory
30+
final class AstClassReflectionFactory
3031
{
32+
/**
33+
* Last rebuilt reflection per class, keyed by file and class node, with the hash of the class content it was built from
34+
*
35+
* @var array<string, array{string, ClassReflection}>
36+
*/
37+
private array $classReflectionsByClass = [];
38+
3139
public function __construct(
32-
private Reflector $reflector,
33-
private ClassReflectionFactory $classReflectionFactory,
40+
private readonly Reflector $reflector,
41+
private readonly ClassReflectionFactory $classReflectionFactory,
42+
private readonly BetterStandardPrinter $betterStandardPrinter,
3443
) {
3544
}
3645

@@ -39,6 +48,15 @@ public function create(Class_|Interface_|Enum_ $classLike, MutatingScope $mutati
3948
$filePath = $mutatingScope->getFile();
4049
$namespace = $mutatingScope->getNamespace();
4150

51+
// the class node is refreshed on every change in it, while its members often stay the same between passes;
52+
// reuse the reflection built from the same content, so its cache key and member caches are not created again
53+
$classKey = $filePath . ':' . $namespace . '\\' . $classLike->name;
54+
$contentHash = hash('xxh128', $this->betterStandardPrinter->print($classLike));
55+
56+
if (isset($this->classReflectionsByClass[$classKey]) && $this->classReflectionsByClass[$classKey][0] === $contentHash) {
57+
return $this->classReflectionsByClass[$classKey][1];
58+
}
59+
4260
$betterReflectionClass = new NodeToReflection()->__invoke(
4361
$this->reflector,
4462
$classLike,
@@ -55,14 +73,18 @@ public function create(Class_|Interface_|Enum_ $classLike, MutatingScope $mutati
5573
: new ReflectionClassAdapter($betterReflectionClass);
5674

5775
// the member caches are keyed by the class reflection cache key,
58-
// so each rebuilt reflection needs its own key not to read members of the former one
59-
return $this->classReflectionFactory->create(
76+
// so each changed class content needs its own key not to read members of the former one
77+
$classReflection = $this->classReflectionFactory->create(
6078
$betterReflectionClass->getName(),
6179
$reflectionClassAdapter,
6280
null,
6381
null,
6482
null,
65-
uniqid($filePath . ':', true)
83+
$filePath . ':' . $contentHash
6684
);
85+
86+
$this->classReflectionsByClass[$classKey] = [$contentHash, $classReflection];
87+
88+
return $classReflection;
6789
}
6890
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Tests\Issues\ClassReflectionRefreshInPlace;
6+
7+
use Iterator;
8+
use PHPUnit\Framework\Attributes\DataProvider;
9+
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
10+
11+
final class ClassReflectionRefreshInPlaceTest extends AbstractRectorTestCase
12+
{
13+
#[DataProvider('provideData')]
14+
public function test(string $filePath): void
15+
{
16+
$this->doTestFile($filePath);
17+
}
18+
19+
public static function provideData(): Iterator
20+
{
21+
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
22+
}
23+
24+
public function provideConfigFilePath(): string
25+
{
26+
return __DIR__ . '/config/configured_rule.php';
27+
}
28+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Rector\Tests\Issues\ClassReflectionRefreshInPlace\Fixture;
4+
5+
final class AddBothTraitsOnce
6+
{
7+
public function run()
8+
{
9+
}
10+
}
11+
12+
?>
13+
-----
14+
<?php
15+
16+
namespace Rector\Tests\Issues\ClassReflectionRefreshInPlace\Fixture;
17+
18+
final class AddBothTraitsOnce
19+
{
20+
use \Rector\Tests\Issues\ClassReflectionRefreshInPlace\Source\OtherTrait;
21+
use \Rector\Tests\Issues\ClassReflectionRefresh\Source\SomeTrait;
22+
public function run()
23+
{
24+
}
25+
}
26+
27+
?>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Tests\Issues\ClassReflectionRefreshInPlace\Source;
6+
7+
use PhpParser\Node;
8+
use PhpParser\Node\Name\FullyQualified;
9+
use PhpParser\Node\Stmt\Class_;
10+
use PhpParser\Node\Stmt\TraitUse;
11+
use PHPStan\Reflection\ClassReflection;
12+
use Rector\Rector\AbstractRector;
13+
use Rector\Reflection\ReflectionResolver;
14+
use Rector\RuleDoc\RuleDefinition;
15+
16+
/**
17+
* Changes the same class node in place right after AddTraitByReflectionRector did,
18+
* so it adds the trait again on every pass unless the class reflection is rebuilt for the same node again
19+
*/
20+
final class AddOtherTraitByReflectionRector extends AbstractRector
21+
{
22+
public function __construct(
23+
private readonly ReflectionResolver $reflectionResolver
24+
) {
25+
}
26+
27+
public function getRuleDefinition(): RuleDefinition
28+
{
29+
return new RuleDefinition('', []);
30+
}
31+
32+
/**
33+
* @return array<class-string<Node>>
34+
*/
35+
public function getNodeTypes(): array
36+
{
37+
return [Class_::class];
38+
}
39+
40+
/**
41+
* @param Class_ $node
42+
*/
43+
public function refactor(Node $node): ?Class_
44+
{
45+
$classReflection = $this->reflectionResolver->resolveClassReflection($node);
46+
if (! $classReflection instanceof ClassReflection || $classReflection->hasTraitUse(OtherTrait::class)) {
47+
return null;
48+
}
49+
50+
$node->stmts = array_merge([new TraitUse([new FullyQualified(OtherTrait::class)])], $node->stmts);
51+
52+
return $node;
53+
}
54+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Tests\Issues\ClassReflectionRefreshInPlace\Source;
6+
7+
trait OtherTrait
8+
{
9+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Rector\Config\RectorConfig;
6+
use Rector\Tests\Issues\ClassReflectionRefresh\Source\AddTraitByReflectionRector;
7+
use Rector\Tests\Issues\ClassReflectionRefreshInPlace\Source\AddOtherTraitByReflectionRector;
8+
9+
return RectorConfig::configure()
10+
->withRules([AddTraitByReflectionRector::class, AddOtherTraitByReflectionRector::class]);

0 commit comments

Comments
 (0)