Skip to content

Speed up the start of every template render - #5028

Open
Kocal wants to merge 1 commit into
twigphp:3.xfrom
Kocal:perf/render-prologue
Open

Kocal wants to merge 1 commit into
twigphp:3.xfrom
Kocal:perf/render-prologue

Conversation

@Kocal

@Kocal Kocal commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Template::yield() runs once per render, include and embed. It called array_merge($this->blocks, $blocks) even when one side is empty, and Environment::getGlobals() re-checked that the extensions are initialized before returning the already resolved globals.

The merge is now skipped when one side is empty (block names are never numeric, so the result is the same). getGlobals() returns $this->resolvedGlobals first when it is set.

yield() of a small template goes from 554-564 -> 486-497 ns, and getGlobals() from 86-89 -> 43-44 ns.

Comment thread src/Environment.php Resolved
Comment thread src/Template.php
{
$context += $this->env->getGlobals();
$blocks = array_merge($this->blocks, $blocks);
$blocks = $blocks ? ($this->blocks ? array_merge($this->blocks, $blocks) : $blocks) : $this->blocks;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if PHP optimizes the empty-argument case (php/php-src#24404), this change remains better: the PHP shortcut only avoids the copy, which copy-on-write already makes unnecessary, while this check also skips the function call and the linear scan of the $this->blocks keys.

Comment thread src/Environment.php Resolved
`Template::yield()` runs once per render, include and embed. It called `array_merge($this->blocks, $blocks)` even when one side is empty, and `Environment::getGlobals()` re-checked that the extensions are initialized before returning the already resolved globals.

The merge is now skipped when one side is empty (block names are never numeric, so the result is the same). `getGlobals()` returns `$this->resolvedGlobals` first when it is set.

`yield()` of a small template goes from 554-564 -> 486-497 ns, and `getGlobals()` from 86-89 -> 43-44 ns.
@Kocal
Kocal force-pushed the perf/render-prologue branch from 99436fe to 0bd0581 Compare November 15, 2026 08:05
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