Skip to content

perf(container): cache dynamic initializer instances#2153

Merged
xHeaven merged 2 commits into
tempestphp:3.xfrom
xHeaven:fix/dynamic-initializer-cache
Jun 5, 2026
Merged

perf(container): cache dynamic initializer instances#2153
xHeaven merged 2 commits into
tempestphp:3.xfrom
xHeaven:fix/dynamic-initializer-cache

Conversation

@xHeaven

@xHeaven xHeaven commented Jun 5, 2026

Copy link
Copy Markdown
Member

Dynamic initializers were resolved through the container every time an unresolved, non-singleton class was looked up. Because these initializer classes are not themselves singleton-cached, each lookup re-instantiated every registered dynamic initializer and repeated reflection/autowiring work just to call canInitialize().

Reprod

$container->addInitializer(DatabaseInitializer::class);
$container->addInitializer(CacheInitializer::class);

$container->get(Foo::class); // pass1
$container->get(Foo::class); // pass2
$container->get(Foo::class); // pass3

Before

// pass1
new DatabaseInitializer();
new CacheInitializer();

new Foo();

// pass2
new DatabaseInitializer();
new CacheInitializer();

new Foo();

// pass3
new DatabaseInitializer();
new CacheInitializer();

new Foo();

After

// pass1
new DatabaseInitializer();
new CacheInitializer();

new Foo();

// pass2
// DatabaseInitializer, CacheInitializer reused
new Foo();

// pass3
// DatabaseInitializer, CacheInitializer reused
new Foo();

@xHeaven xHeaven requested a review from brendt as a code owner June 5, 2026 11:04
@brendt

brendt commented Jun 5, 2026

Copy link
Copy Markdown
Member

Feel free to merge when CI is done :)

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown

Benchmark Results

Comparison of fix/dynamic-initializer-cache against 3.x (b102c7fe7513675b96bbcdc892c4fb99e49a291c).

Open to see the benchmark results
Benchmark Set Mem. Peak Time Variability
ContainerBench(benchResolveWithDynamicInitializer) - 4.078mb +0.03% 4.548μs -42.98% ±0.66% -34.99%

Generated by phpbench against commit 718e711

Comment thread packages/container/src/GenericContainer.php Outdated
Co-authored-by: Enzo Innocenzi <enzo@innocenzi.dev>
@xHeaven xHeaven force-pushed the fix/dynamic-initializer-cache branch from 913bd75 to 718e711 Compare June 5, 2026 11:20
@xHeaven xHeaven merged commit dbef226 into tempestphp:3.x Jun 5, 2026
76 checks passed
@xHeaven xHeaven deleted the fix/dynamic-initializer-cache branch June 5, 2026 11:48
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.

3 participants