Skip to content

Commit 1f58504

Browse files
committed
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: databricks#776
1 parent 0ae7b78 commit 1f58504

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

sjsonnet/src/sjsonnet/Format.scala

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -574,9 +574,13 @@ object Format {
574574
}
575575
val labels = parsed.labels
576576
val specBits = parsed.specBits
577+
val singleSpecNoStatic = specBits.length == 1 && parsed.staticChars == 0
577578
// Pre-size StringBuilder based on static chars + estimated dynamic content
578-
val output = new java.lang.StringBuilder(parsed.staticChars + specBits.length * 8)
579-
appendLeading(output, parsed)
579+
val output =
580+
if (singleSpecNoStatic) null
581+
else new java.lang.StringBuilder(parsed.staticChars + specBits.length * 8)
582+
if (!singleSpecNoStatic) appendLeading(output, parsed)
583+
var singleFormatted: String = null
580584
var i = 0
581585
var idx = 0
582586
// Use while-loop instead of for/zipWithIndex to avoid iterator allocation
@@ -731,8 +735,11 @@ object Format {
731735
i += 1
732736
formattedValue
733737
}
734-
output.append(cooked0)
735-
appendLiteral(output, parsed, idx)
738+
if (singleSpecNoStatic) singleFormatted = cooked0
739+
else {
740+
output.append(cooked0)
741+
appendLiteral(output, parsed, idx)
742+
}
736743
idx += 1
737744
}
738745

@@ -741,7 +748,7 @@ object Format {
741748
"Too many values to format: %d, expected %d".format(valuesArr.length, i)
742749
)
743750
}
744-
output.toString()
751+
if (singleSpecNoStatic) singleFormatted else output.toString()
745752
}
746753

747754
/**

0 commit comments

Comments
 (0)