Skip to content

Speed up the with tag by adding the globals to the new context in place - #5009

Open
nicolas-grekas wants to merge 1 commit into
twigphp:3.xfrom
nicolas-grekas:with-tag-globals-merge-3x
Open

nicolas-grekas wants to merge 1 commit into
twigphp:3.xfrom
nicolas-grekas:with-tag-globals-merge-3x

Conversation

@nicolas-grekas

Copy link
Copy Markdown
Contributor

$vars + $context + $this->env->getGlobals() copies the whole context twice. Adding the globals in place saves one copy per with tag, 2.2k instructions with a context of 40 variables.

Comment thread src/Node/WithNode.php Resolved
@nicolas-grekas
nicolas-grekas force-pushed the with-tag-globals-merge-3x branch from 7edd2d8 to b15f080 Compare October 20, 2026 12:09
@nicolas-grekas
nicolas-grekas force-pushed the with-tag-globals-merge-3x branch from b15f080 to 60d1921 Compare October 27, 2026 14:30
@GromNaN

GromNaN commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Nice improvement, the two statements avoid one full copy of the context.

An optional idea, not blocking: part of the work could be decided at compile time.

  1. With only, the context is known to be empty, so the generated code could be reduced to a single statement and skip the $context = []; assignment:

    $context = $vars + $this->env->getGlobals();

    The precedence stays the same (with variables, then globals).

  2. When the variables node is an empty ArrayExpression ({% with {} %}), WithNode::compile() could skip the is_iterable() check, toArray() and the context merge entirely, and only add the globals when only is set.

The second case is rare in real templates, and a variable that is empty at runtime cannot be detected by the compiler, so I would not expect a measurable gain there. The first case is cheap to implement and makes the generated code shorter.

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