Skip to content

perf: inline numeric fast path in array comparison#693

Open
He-Pin wants to merge 1 commit intodatabricks:masterfrom
He-Pin:perf/inline-numeric-array-compare
Open

perf: inline numeric fast path in array comparison#693
He-Pin wants to merge 1 commit intodatabricks:masterfrom
He-Pin:perf/inline-numeric-array-compare

Conversation

@He-Pin
Copy link
Copy Markdown
Contributor

@He-Pin He-Pin commented Apr 5, 2026

Motivation

Array comparison in Jsonnet compares elements pairwise. When both elements are Val.Num, the current code path goes through the generic comparison dispatch, adding virtual call and type-check overhead for the most common case.

Key Design Decision

Add an inline fast path that directly compares Val.Num values when both operands have the numeric type tag, avoiding the generic dispatch entirely.

Modification

  • Add Val.Num type check before generic comparison dispatch
  • Directly compare double values when both are numeric
  • ~16 lines changed

Benchmark Results

JMH (JVM, 3 iterations warmup + 3 measurement)

Benchmark Master (ms/op) This PR (ms/op) Change
bench.02 50.427 ± 38.9 46.276 ± 2.6 -8.2%
comparison2 85.854 ± 188.7 69.744 ± 18.1 -18.8%
realistic2 73.458 ± 66.7 66.519 ± 10.4 -9.4%

Analysis

The comparison2 benefit (-18.8%) is expected since that benchmark performs many array comparisons with numeric elements. This is a minimal-risk optimization (16 lines, zero semantic change) that adds a type check fast path.

References

  • Upstream: jit branch experiment

Result

All 49 tests pass. All benchmarks positive, no regressions.

Inline Val.Num type check in the array comparison while loop to avoid
polymorphic recursive compare() dispatch per element. For numeric
array comparisons (e.g. 1M elements), this eliminates 1M recursive
method calls with 5-branch pattern matching overhead.

Uses asDouble (not raw extraction) to preserve NaN error behavior —
std.log(-1) etc. can produce NaN in Val.Num, and asDouble correctly
throws 'not a number', matching the official C++ jsonnet behavior.

Uses java.lang.Double.compare() instead of compareTo() to avoid
autoboxing overhead.

Upstream: jit branch commit 62437d8
@He-Pin He-Pin marked this pull request as ready for review April 5, 2026 13:50
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