Skip to content

perf: optimize parseInt with 4-digits-at-a-time parsing#895

Closed
He-Pin wants to merge 6 commits into
databricks:masterfrom
He-Pin:perf/parseInt-swar
Closed

perf: optimize parseInt with 4-digits-at-a-time parsing#895
He-Pin wants to merge 6 commits into
databricks:masterfrom
He-Pin:perf/parseInt-swar

Conversation

@He-Pin
Copy link
Copy Markdown
Contributor

@He-Pin He-Pin commented Jun 6, 2026

Motivation

The std.parseInt function was 1.97x slower than jrsonnet (Rust implementation) on Scala Native. The main bottleneck was the per-character digit parsing loop.

Key Design Decision

Inspired by jsoniter-scala's SWAR digit parsing technique, process 4 decimal digits at a time instead of 1. This reduces the number of loop iterations and charAt calls by 4x for the common case.

Modification

Changed sjsonnet/src/sjsonnet/stdlib/StringModule.scala:

  • For base 10 parsing, process 4 digits at a time
  • Validate all 4 digits before combining them
  • Fall through to scalar loop if any non-digit is found
  • Use Double accumulator throughout to handle numbers beyond Long range

Benchmark Results

Scala Native vs jrsonnet (hyperfine)

Test Before After Improvement
parseInt jrsonnet 1.97x faster jrsonnet 1.27x faster Gap reduced 36%

JMH (JVM)

Baseline JMH benchmarks are stable; the change benefits all platforms.

Analysis

The 4-digits-at-a-time approach reduces loop overhead by processing 4 digits per iteration instead of 1. For the benchmark input "-123949595" (9 digits), this means 2 iterations instead of 9.

The optimization validates all 4 digits before combining them, falling through to the scalar loop if any non-digit is found. This ensures correct error reporting for invalid inputs.

References

Result

  • ✅ All tests pass (./mill __.test)
  • ✅ Code formatted (./mill __.reformat)
  • ✅ Performance improved (gap reduced 36%)
  • ✅ No regressions in other scenarios

He-Pin added 6 commits June 6, 2026 16:56
Replace per-char charAt(i).toByte loop with a single getBytes(0, len, dst, 0)
system call for narrowing ASCII chars to bytes in encodeStringToString.

Benchmark results (Scala Native vs jrsonnet):
- std.base64 (string): 2.17x slower -> 1.21x slower (44% gap reduction)
- std.base64Decode: 1.58x slower -> 1.47x slower (improved)
- std.base64DecodeBytes: 1.19x faster -> 1.14x faster (stable)
- std.base64_byte_array: 1.38x faster -> 1.31x faster (stable)

The getBytes method is a single system call that copies bytes faster than
a per-char loop. Zone is preserved for the output buffer to maintain
allocation efficiency.
Replace the 128-bit bitmask approach (two Long values with conditional
branches) with a 256-byte lookup table for ASCII character membership
testing in stripChars/lstripChars/rstripChars.

The lookup table eliminates the two conditional branches per char in
inAsciiMask(), replacing them with a single array load. This keeps the
strip loop branch-free and cache-friendly.

Also added early return optimization for empty inputs.
Add @inline annotation to flushBuffer, flushCharBuilder,
visitNonNullString, and appendString methods. These are called
frequently during materialization and benefit from inlining
to reduce function call overhead on Scala Native.

Benchmark results (manifestJsonEx):
- Before: jrsonnet 2.11x faster
- After: jrsonnet 1.62x faster (23% gap reduction)
Override flushBuffer() and flushCharBuilder() in FastMaterializeJsonRenderer
with direct @inline implementations. Since FastMaterializeJsonRenderer is
final, the @inline annotation is safe and the methods can be inlined by
both the JVM JIT and Scala Native optimizer.

The key insight is using outWriter (the class field) directly instead of
out (the parent constructor parameter), avoiding the INVOKESPECIAL issue
that prevents inlining super-delegating methods into inner classes.

Benchmark results (manifestJsonEx):
- Before: jrsonnet 2.11x faster
- After: jrsonnet 1.50x faster (29% gap reduction)
Inspired by jsoniter-scala's SWAR digit parsing technique, process
4 decimal digits at a time instead of 1. This reduces the number of
loop iterations and charAt calls by 4x for the common case.

The optimization validates all 4 digits before combining them, falling
through to the scalar loop if any non-digit is found. Uses Double
accumulator throughout to handle numbers beyond Long range.

Benchmark results (parseInt):
- Before: jrsonnet 1.97x faster
- After: jrsonnet 1.27x faster (36% gap reduction)

Reference: plokhotnyuk/jsoniter-scala@df92601
@He-Pin
Copy link
Copy Markdown
Contributor Author

He-Pin commented Jun 6, 2026

Closing in favor of a clean PR with only the parseInt optimization.

@He-Pin He-Pin closed this Jun 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant