Skip to content

Commit 154c738

Browse files
committed
perf: use pre-allocated char buffers for Native compareStrings
Replace per-call `new Array[Char](n)` allocation with module-level pre-allocated buffers in Scala Native's compareStrings. Safe because Scala Native is single-threaded (mirrors the JVM ThreadLocal approach).
1 parent f0d8005 commit 154c738

1 file changed

Lines changed: 12 additions & 4 deletions

File tree

sjsonnet/src-native/sjsonnet/CharSWAR.scala

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,21 +159,29 @@ object CharSWAR {
159159
// compareStrings — codepoint-correct string comparison
160160
// =========================================================================
161161

162+
// Pre-allocated char buffers for string comparison.
163+
// Scala Native is single-threaded, so module-level buffers are safe.
164+
private final val CMP_BUF_SIZE = 32768
165+
private val cmpBuf1: Array[Char] = new Array[Char](CMP_BUF_SIZE)
166+
private val cmpBuf2: Array[Char] = new Array[Char](CMP_BUF_SIZE)
167+
162168
/**
163169
* Compare two strings by Unicode codepoint values. Uses bulk getChars + tight array loop for
164170
* LLVM auto-vectorization. Surrogate checks deferred to mismatch point only.
171+
* Pre-allocated module-level buffers avoid per-call allocation overhead.
165172
*/
166173
def compareStrings(s1: String, s2: String): Int = {
167174
if (s1 eq s2) return 0
168175
val n1 = s1.length
169176
val n2 = s2.length
170177
val minLen = math.min(n1, n2)
171178

172-
if (minLen < 16) return compareStringsScalar(s1, n1, s2, n2)
179+
if (minLen < 16 || n1 > CMP_BUF_SIZE || n2 > CMP_BUF_SIZE)
180+
return compareStringsScalar(s1, n1, s2, n2)
173181

174-
// Bulk-copy to arrays — enables LLVM auto-vectorization
175-
val c1 = new Array[Char](n1)
176-
val c2 = new Array[Char](n2)
182+
// Bulk-copy to pre-allocated arrays — zero allocation, enables LLVM auto-vectorization
183+
val c1 = cmpBuf1
184+
val c2 = cmpBuf2
177185
s1.getChars(0, n1, c1, 0)
178186
s2.getChars(0, n2, c2, 0)
179187

0 commit comments

Comments
 (0)