From 1f58504d7d0778e5f55d23db68790c554fd872d2 Mon Sep 17 00:00:00 2001 From: He-Pin Date: Sun, 10 May 2026 14:38:06 +0800 Subject: [PATCH] perf: skip builders for single-spec formats Motivation: Short format strings such as %08d or %20s have exactly one dynamic value and no static literal text, so the generic format path was allocating and appending through a StringBuilder only to return that single formatted value. Modification: Detect the single-spec/no-static-literal case in Format.format and return the computed formatted value directly after preserving all existing arity checks. Result: The repeat_format regression improves from 0.190 ms/op on upstream master to 0.133 ms/op locally, while large_string_template remains effectively neutral and the full Mill test matrix passes. References: Source idea: https://github.com/databricks/sjsonnet/pull/776 --- sjsonnet/src/sjsonnet/Format.scala | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/sjsonnet/src/sjsonnet/Format.scala b/sjsonnet/src/sjsonnet/Format.scala index 212e2600..9d272d49 100644 --- a/sjsonnet/src/sjsonnet/Format.scala +++ b/sjsonnet/src/sjsonnet/Format.scala @@ -574,9 +574,13 @@ object Format { } val labels = parsed.labels val specBits = parsed.specBits + val singleSpecNoStatic = specBits.length == 1 && parsed.staticChars == 0 // Pre-size StringBuilder based on static chars + estimated dynamic content - val output = new java.lang.StringBuilder(parsed.staticChars + specBits.length * 8) - appendLeading(output, parsed) + val output = + if (singleSpecNoStatic) null + else new java.lang.StringBuilder(parsed.staticChars + specBits.length * 8) + if (!singleSpecNoStatic) appendLeading(output, parsed) + var singleFormatted: String = null var i = 0 var idx = 0 // Use while-loop instead of for/zipWithIndex to avoid iterator allocation @@ -731,8 +735,11 @@ object Format { i += 1 formattedValue } - output.append(cooked0) - appendLiteral(output, parsed, idx) + if (singleSpecNoStatic) singleFormatted = cooked0 + else { + output.append(cooked0) + appendLiteral(output, parsed, idx) + } idx += 1 } @@ -741,7 +748,7 @@ object Format { "Too many values to format: %d, expected %d".format(valuesArr.length, i) ) } - output.toString() + if (singleSpecNoStatic) singleFormatted else output.toString() } /**