From 3798dc1772f5e81bb198d8eeb5cb147ae2805042 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 14 Nov 2026 22:05:11 +0100 Subject: [PATCH] Speed up the `merge` filter and the `include` and `embed` tags with variables `CoreExtension::merge()` merged its arguments two by two and copied an intermediate array each time. With `{% include ... with {...} %}`, that intermediate array is the whole context. It now validates the arguments and calls `array_merge()` once. Errors are unchanged. A context of 35 variables + 3 variables goes from 435-485 -> 269-293 ns, and two 3-variable arrays from 299-372 -> 144-153 ns. --- CHANGELOG | 1 + src/Extension/CoreExtension.php | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index a3653427c97..fb6bc6112dd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -21,6 +21,7 @@ * Add a way to mark a `Twig\Markup` instance as safe for some escaping strategies only * Make `Environment::getExtension()` return the runtime of an extension class registered with `AttributeExtension` * Make `Environment::getRuntime()` fall back to the registered extension of the same class + * Speed up the `merge` filter and the `include` and `embed` tags with variables # 3.30.0 (2026-09-25) diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index 410597bbb1e..8aa970334a2 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -732,17 +732,19 @@ public static function urlencode($url): string */ public static function merge(...$arrays): array { - $result = []; - foreach ($arrays as $argNumber => $array) { + if (\is_array($array)) { + continue; + } + if (!is_iterable($array)) { throw new RuntimeError(\sprintf('The "merge" filter expects a sequence or a mapping, got "%s" for argument %d.', get_debug_type($array), $argNumber + 1)); } - $result = array_merge($result, self::toArray($array)); + $arrays[$argNumber] = self::toArray($array); } - return $result; + return array_merge(...$arrays); } /**