Skip to content

Speed up getCacheKey() in ChainLoader and FilesystemLoader for template names already resolved - #5027

Open
Kocal wants to merge 1 commit into
twigphp:3.xfrom
Kocal:perf/loader-cache-key-memo
Open

Kocal wants to merge 1 commit into
twigphp:3.xfrom
Kocal:perf/loader-cache-key-memo

Conversation

@Kocal

@Kocal Kocal commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Environment::getTemplateClass() calls the loader's getCacheKey() on every include, embed, extends and import. ChainLoader asked each loader exists() again, and FilesystemLoader normalized the name and stripped the root path again.

Both loaders now remember the key per template name. The memo is cleared where the existing caches are cleared (addLoader(), addPath(), prependPath()).

getTemplateClass() goes from 531-542 -> 312-319 ns with a FilesystemLoader, and 876-947 -> 316-320 ns behind a ChainLoader. A page with 500 includes goes from 1.275-1.319 -> 0.997-1.060 ms. Caveat: like the existing $hasSourceCache, the ChainLoader memo does not see a sub-loader changed after the fact ($chain->getLoaders()[0]->addPath()), and a FilesystemLoader subclass that empties the protected $cache by hand keeps the old key.

…template names already resolved

`Environment::getTemplateClass()` calls the loader's `getCacheKey()` on every `include`, `embed`, `extends` and `import`. `ChainLoader` asked each loader `exists()` again, and `FilesystemLoader` normalized the name and stripped the root path again.

Both loaders now remember the key per template name. The memo is cleared where the existing caches are cleared (`addLoader()`, `addPath()`, `prependPath()`).

`getTemplateClass()` goes from 531-542 -> 312-319 ns with a `FilesystemLoader`, and 876-947 -> 316-320 ns behind a `ChainLoader`. A page with 500 includes goes from 1.275-1.319 -> 0.997-1.060 ms. Caveat: like the existing `$hasSourceCache`, the `ChainLoader` memo does not see a sub-loader changed after the fact (`$chain->getLoaders()[0]->addPath()`), and a `FilesystemLoader` subclass that empties the protected `$cache` by hand keeps the old key.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants