Skip to content

Optimize core Java coders and windowing hot paths - #41535

Open
reuvenlax wants to merge 3 commits into
apache:masterfrom
reuvenlax:perf/core-coders
Open

reuvenlax wants to merge 3 commits into
apache:masterfrom
reuvenlax:perf/core-coders

Conversation

@reuvenlax

Copy link
Copy Markdown
Contributor
  • BitConverters: eliminate per-call byte[] allocations on big/little-endian encode/decode.
  • InstantCoder: encode/decode directly with primitive shifts and return canonical BoundedWindow.TIMESTAMP_MIN_VALUE / TIMESTAMP_MAX_VALUE singletons.
  • LengthPrefixCoder: delegate ByteArrayCoder and StringUtf8Coder directly to NESTED context and pool reusable byte buffers for other inner coders.
  • IntervalWindow: encode/decode window duration directly via VarInt without allocating Duration objects and avoid Duration allocation in maxTimestamp().
  • PaneInfo: return this in withElementMetadata when unchanged and avoid duplicate chooseEncoding() calls in PaneInfoCoder.encode().
  • Add unit tests in LengthPrefixCoderTest and JMH microbenchmarks in CoreCodersBenchmark.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 Review Summary

This PR introduces well-targeted, low-risk performance optimizations to hot-path coders (BitConverters, InstantCoder, LengthPrefixCoder, IntervalWindow, and PaneInfo), alongside unit tests and JMH microbenchmarks. All wire formats and error semantics are preserved while eliminating unnecessary allocations (byte[], Duration, Instant, ByteArrayOutputStream, and PaneInfo instances).

🔍 General Feedback

  • The LengthPrefixCoder fast-path for ByteArrayCoder and StringUtf8Coder cleanly leverages their existing Context.NESTED length-prefixing behavior, and the bounded ThreadLocal buffer pool safely handles reentrancy and large payloads.
  • Arithmetic in IntervalWindow and IntervalWindowCoder matches Joda-Time FieldUtils.safeSubtract semantics via Math.subtractExact without intermediate Duration allocations.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

@github-actions github-actions Bot added java core size/m M: 50-249 lines changed labels Nov 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers (or comment /summarize-failures for a summary of the failing checks).

@github-actions github-actions Bot added size/l L: 250-999 lines changed and removed size/m M: 50-249 lines changed labels Nov 20, 2026
@reuvenlax
reuvenlax requested a review from Abacn November 21, 2026 00:02
@Abacn

Abacn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Optimization-by-Optimization Trade-Off Evaluation

Optimization Readability / Complexity Security / Safety Expected Perf Benefit Worth Doing?
1. PaneInfo & PaneInfoCoder (withElementMetadata identity + remove duplicate chooseEncoding) Improved (+4 lines; removes a redundant call) Safe (PaneInfo is final/immutable) High — eliminates a PaneInfo allocation on nearly every WindowedValue decode ✅ Yes (clear win)
2. InstantCoder (return canonical TIMESTAMP_MIN_VALUE / TIMESTAMP_MAX_VALUE) Clean (+8 lines, self-evident) Safe (Instant is immutable; verified no <clinit> cycle with BoundedWindow) Medium–High — avoids new Instant for default batch/sentinel timestamps; 2 predictable long compares otherwise ✅ Yes (clear win)
3. IntervalWindow & IntervalWindowCoder (direct VarInt + Math.subtractExact, avoid Duration) Good (minor coupling note: bypasses durationCoder field at L158) Safe (exact wire-format & EOFException/UTFDataFormatException match to VarLongCoder) High — eliminates Duration allocation, Long boxing, and Joda chronology overhead on every window encode/decode/maxTimestamp() ✅ Yes (clear win)
4. LengthPrefixCoder fast path (ByteArrayCoder / StringUtf8Coder -> Context.NESTED) Very clean (+6 lines) Safe (both constructors are private so no subclasses; wire format identical; truncated decode now strictly throws EOFException/CoderException instead of silently truncating) Very High — eliminates an entire buffer allocation + extra copy + ByteStreams.limit wrapper for the two most common wrapped coders ✅ Yes (clear win)
5. LengthPrefixCoder ThreadLocal<BufferPool> + custom ReusableByteArrayOutputStream Poor (+95 lines of custom linked-list pool + hand-rolled ByteArrayOutputStream with subtle JDK-8 signed-overflow ensureCapacity math) Moderate concern — retains up to 256 KiB/thread of unzeroed user payload bytes strongly in ThreadLocal (no SoftReference), ClassLoader leak risk, OutputStream aliasing Potentially High for nested/complex coders (KvCoder, RowCoder, AvroCoder) over Fn API where ByteArrayOutputStream allocates + resizes + synchronizes every call — but unquantified (no JMH numbers posted) ⚠️ Borderline — only worth it if JMH proves substantial gain, and needs SoftReference + simpler ensureCapacity
6. BitConverters.writeBigEndianLong (ThreadLocal<ScratchHolder> 8-byte buffer) Poor (2 lines -> 35 lines of ThreadLocal + ScratchHolder + try/finally + reentrancy fallback + asymmetric readBigEndianLong) Low–Moderate concern — ClassLoader leak via strong ThreadLocal<ScratchHolder>, OutputStream buffer-reference aliasing Small / Unproven — saves one 24-byte TLAB allocation while paying ThreadLocal.get() + checkout/finally overhead; note the identical approach was 18–20% slower on readBigEndianLong and had to be reverted! ❌ Probably not worth it unless JMH shows a compelling real-world win on realistic streams

Ran some microbenchmarks on my sides:

Optimization Path / Benchmark Before (ops/us) After (ops/us) Throughput Delta Before (B/op) After (B/op)
1. BitConverters
bitConvertersLongEncodeByteString 205.85 ± 3.33 187.72 ± 3.23 -8.8% 24.0 0.0
bitConvertersLongEncodeSyncBaos 100.04 ± 2.23 101.78 ± 1.88 +1.7% (noise) 24.0 0.0
bitConvertersLongEncodePolymorphic 143.96 ± 3.68 147.04 ± 19.08 +2.1% (noise) 24.0 0.0
instantEncodeByteString (uses BitConverters) 211.76 ± 1.16 179.85 ± 1.05 -15.1% 24.0 0.0
bitConvertersLongDecodePolymorphic (reverted control) 96.81 ± 2.33 95.21 ± 2.94 -1.6% 48.0 48.0
2. InstantCoder
instantDecodeNormal 221.82 ± 4.45 223.04 ± 2.15 +0.5% 24.0 24.0
instantDecodeMinValue 221.66 ± 5.05 405.22 ± 5.39 +82.8% 24.0 0.0
instantDecodeMaxValue 222.91 ± 6.76 371.69 ± 8.85 +66.7% 24.0 0.0
3. LengthPrefixCoder Fast Path
lengthPrefixByteArrayEncode (256B) 65.65 ± 1.11 212.99 ± 1.02 +224.4% 320.0 0.0
lengthPrefixByteArrayDecode (256B) 54.87 ± 1.16 65.47 ± 1.50 +19.3% 272.0 272.0
lengthPrefixStringEncode 30.49 ± 0.32 36.04 ± 0.81 +18.2% 368.0 232.0
lengthPrefixStringDecode 32.84 ± 2.24 38.97 ± 0.28 +18.7% 280.0 280.0
**4. LengthPrefixCoder BufferPool (isolated w/ VarIntCoder) **
lengthPrefixKvSmallEncode (~70B) 23.65 ± 0.18 28.31 ± 0.09 +19.7% 520.0 232.0
lengthPrefixKvLargeEncode (4 KiB) 3.28 ± 0.11 9.36 ± 0.20 +184.9% 12384.3 0.0
lengthPrefixNestedPooledEncode (depth-2 pool) 25.23 ± 0.26 47.86 ± 1.16 +89.7% 216.0 0.0
lengthPrefixOversizedEncode (80 KiB > 64 KiB cap) 0.18 ± 0.03 0.18 ± 0.00 -1.4% 245885.2 246109.2
5. IntervalWindow
intervalWindowMaxTimestamp 832.21 ± 29.47 845.19 ± 22.29 +1.6% 24.0 24.0
intervalWindowCoderEncode (includes BitConverters) 153.70 ± 34.71 143.10 ± 3.09 -6.9% 24.0 0.0
intervalWindowCoderDecode 74.94 ± 1.23 75.55 ± 1.15 +0.8% 72.0 72.0
intervalWindowCoderByteSize 649.43 ± 24.99 767.52 ± 6.97 +18.2% 0.0 0.0
6. PaneInfo
paneInfoWithElementMetadataUnchanged 465.95 ± 9.70 1935.52 ± 8.45 +315.4% 40.0 0.0
paneInfoCoderEncodeFirst 980.09 ± 57.19 996.94 ± 50.05 +1.7% 0.0 0.0
paneInfoCoderEncodeTwoIndices 704.78 ± 12.95 717.45 ± 20.06 +1.8% 0.0 0.0
paneInfoCoderDecodeFirst 137.42 ± 5.21 213.95 ± 1.65 +55.7% 72.0 32.0
7. End-to-End Composite
windowedValueEncode 25.70 ± 0.46 24.71 ± 0.93 -3.9% 280.0 232.0
windowedValueDecode 18.80 ± 0.28 19.56 ± 1.18 +4.0% 544.0 480.0

From the results it appears we should simply revert the BitConverters changes (and its tests). We may also want to consolidates/simplify test cases, avoid change-detection tests, as the main change looks thin while there are many unit tests testing line-by-line behaviors

- BitConverters: eliminate per-call byte[] allocations on big/little-endian encode/decode.
- InstantCoder: encode/decode directly with primitive shifts and return canonical
  BoundedWindow.TIMESTAMP_MIN_VALUE / TIMESTAMP_MAX_VALUE singletons.
- LengthPrefixCoder: delegate ByteArrayCoder and StringUtf8Coder directly to NESTED
  context and pool reusable byte buffers for other inner coders.
- IntervalWindow: encode/decode window duration directly via VarInt without allocating
  Duration objects and avoid Duration allocation in maxTimestamp().
- PaneInfo: return `this` in withElementMetadata when unchanged and avoid duplicate
  chooseEncoding() calls in PaneInfoCoder.encode().
- Add unit tests in LengthPrefixCoderTest and JMH microbenchmarks in CoreCodersBenchmark.
@reuvenlax

Copy link
Copy Markdown
Contributor Author

I took another look, because I got better results than you on my benchmarking run (for BitConverters). However after looking, I think you were right - the error bars were large, and the results I got were within the noise.

Rewrote the BitConverters change to avoid the use of the ThreadLocal, and results look much better. bigEndianLongEncode is now twice as fast, and instantEncode is nearly twice as fast.

LengthPrefixCoder rewritten to use SoftReference, as suggested.

Cleaned up test classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants