Skip to content

Borrow loop and set variable names from the chunk - #1062

Merged
Keats merged 1 commit into
Keats:masterfrom
patrick-immometrica:perf/borrow-variable-names
Nov 20, 2026
Merged

Keats merged 1 commit into
Keats:masterfrom
patrick-immometrica:perf/borrow-variable-names

Conversation

@patrick-immometrica

Copy link
Copy Markdown
Contributor

Every time a for loop starts, StoreLocal copies the name of the loop variable (and of the key in for k, v in ...) into a new String. {% set %} and {% set_global %} do the same on every execution to have a key to insert with, and when the variable already exists that String is dropped again right away. So an inner loop costs one allocation per iteration of the outer one, and an assignment in a loop costs one per iteration.

The names live in the instructions of a chunk that is borrowed for the whole render (&'tera Chunk), so ForLoop and State::set_variables can hold a &'tera str instead. ForLoop gets a lifetime for that; it is crate-private and the public State API is untouched. __tera_context and the list of available variables in the undefined-variable error still build owned strings like before.

Allocations per render with 100 products (release build, counting global allocator):

before after
nested loop 108 7
big-table from the benches (100x100) 113 12
set_global in a loop 306 204
two set in a loop 1,109 908
{# nested loop #}
{% for p in products %}{% for t in p.tags %}{{ t }}{% if not loop.last %}, {% endif %}{% endfor %}
{% endfor %}

{# set_global in a loop #}
{% set count = 0 %}{% for p in products %}{% set_global count = count + 1 %}{% endfor %}{{ count }}

{# two set in a loop #}
{% for p in products %}{% set total = p.price * 2 %}{% set label = p.name ~ " (" ~ p.id ~ ")" %}{{ label }}: {{ total }}
{% endfor %}

In time, the nested loop goes from 15.6 to 13.3 µs and the set_global loop from 6.2 to 4.9 µs (best of three interleaved runs). big-table doesn't move, 100 allocations disappear next to 10,000 writes. The output is byte-identical in all of them.

The names of loop variables and of variables assigned with set/set_global
were copied into a new String every time a loop started or an assignment
ran. They live in the chunk for the whole render, so keep a reference
instead.
@patrick-immometrica
patrick-immometrica marked this pull request as ready for review November 15, 2026 19:27
@Keats
Keats merged commit 1eb0b9c into Keats:master Nov 20, 2026
5 checks passed
@patrick-immometrica
patrick-immometrica deleted the perf/borrow-variable-names branch November 20, 2026 15:24
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.

2 participants