Skip to content

Build literal kwargs once at compile time - #1061

Merged
Keats merged 1 commit into
Keats:masterfrom
patrick-immometrica:perf/fold-constant-kwargs
Nov 20, 2026
Merged

Keats merged 1 commit into
Keats:masterfrom
patrick-immometrica:perf/fold-constant-kwargs

Conversation

@patrick-immometrica

Copy link
Copy Markdown
Contributor

When a filter, test or function is called with arguments, the VM builds the kwargs map on every call: keys and values are pushed, then BuildMap collects them into a temporary Vec, turns each key into an Arc<str>, builds the map and wraps it in an Arc. That's four allocations for something like truncate(length=10), repeated on every loop iteration although the result is always the same.

If every argument is a literal, the compiler now builds the map itself and emits a single LoadConst, like the parser already does for literal maps and arrays. A call with at least one non-literal argument compiles exactly as before, and so does a call without arguments (those already share one empty map). Kwargs only hands out references, so sharing the map between calls isn't observable from a filter.

Numbers for this template over 100 products (release build, counting global allocator, time is the best of three interleaved runs):

{% for p in products %}{{ p.name | upper }} {{ p.tags | join(sep=", ") }} {{ p.missing | default(value="-") }} {{ p.name | truncate(length=10) }} {{ p.tags | length }}
{% endfor %}
per render before after
allocations 2,809 1,309
bytes allocated 259 KB 53 KB
time 105 µs 71 µs

Templates without literal kwargs have the same allocation counts as before and the output is byte-identical everywhere I compared it.

The two compiler snapshots that changed are the ones calling a filter with lang="fr". I added one more input with a literal, a non-literal and a mixed call next to each other.

When every argument of a filter, test or function call is a literal, the
kwargs map is the same on every call. Emit it as a single constant instead
of rebuilding it each time the call runs.
@patrick-immometrica
patrick-immometrica marked this pull request as ready for review November 15, 2026 19:26
@Keats
Keats merged commit 1177d10 into Keats:master Nov 20, 2026
5 checks passed
@Keats

Keats commented Nov 20, 2026

Copy link
Copy Markdown
Owner

Thanks!

@patrick-immometrica
patrick-immometrica deleted the perf/fold-constant-kwargs branch November 20, 2026 14:49
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