From 19a267c99655da3c42b45b1d10b1dc0d07965fa7 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sat, 14 Nov 2026 22:05:12 +0100 Subject: [PATCH] Speed up merging the class lists in `html_cva()` recipes `Cva::apply()` grew its class list with `[...$classes, ...$more]` for each recipe, compound variant and default variant, which copied the whole list each time. It now collects the lists and merges them once with `array_merge()`. This is a small gain: 1218-1230 -> 1163-1173 ns per call on a button recipe with 3 variants, 3 sizes and 2 compound variants. --- CHANGELOG | 1 + extra/html-extra/Cva.php | 13 ++++++------- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index a3653427c97..a47dd5a378a 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 merging the class lists in `html_cva()` recipes # 3.30.0 (2026-09-25) diff --git a/extra/html-extra/Cva.php b/extra/html-extra/Cva.php index 35abc766913..906e7314d64 100644 --- a/extra/html-extra/Cva.php +++ b/extra/html-extra/Cva.php @@ -88,30 +88,29 @@ public function __construct( public function apply(array $recipes, ?string ...$additionalClasses): string { - $classes = $this->base; + $classLists = [$this->base]; // Resolve recipes against variants foreach ($recipes as $recipeName => $recipeValue) { $recipeClasses = $this->variants[$recipeName][self::toVariantName($recipeValue)] ?? []; - $classes = [...$classes, ...(array) $recipeClasses]; + $classLists[] = (array) $recipeClasses; } // Resolve compound variants foreach ($this->compoundVariants as $compound) { - $compoundClasses = $this->resolveCompoundVariant($compound, $recipes) ?? []; - $classes = [...$classes, ...$compoundClasses]; + $classLists[] = $this->resolveCompoundVariant($compound, $recipes) ?? []; } // Apply default variants if specific recipes aren't provided foreach ($this->defaultVariants as $defaultVariantName => $defaultVariantValue) { if (!isset($recipes[$defaultVariantName])) { $variantClasses = $this->variants[$defaultVariantName][self::toVariantName($defaultVariantValue)] ?? []; - $classes = [...$classes, ...(array) $variantClasses]; + $classLists[] = (array) $variantClasses; } } - $classes = [...$classes, ...array_values($additionalClasses)]; + $classLists[] = array_values($additionalClasses); - $classes = implode(' ', array_filter($classes, 'is_string')); + $classes = implode(' ', array_filter(array_merge(...$classLists), 'is_string')); if (isset(self::$classListCache[$classes])) { return self::$classListCache[$classes];