Skip to content

Fix stream latency and reduce codec allocations with measured performance improvements - #13

Merged
cinderblocks merged 28 commits into
cinderblocks:masterfrom
jogibear9988:perf/stream-memory-and-reuse
Nov 3, 2026
Merged

cinderblocks merged 28 commits into
cinderblocks:masterfrom
jogibear9988:perf/stream-memory-and-reuse

Conversation

@jogibear9988

@jogibear9988 jogibear9988 commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

ZInputStream could refill compressed input while decoded output remained buffered, and ZOutputStream.Flush did not expose pending compressed messages. This PR fixes those behaviors, releases retained caller/source buffers, and reduces codec allocation and reset overhead. The follow-up performance review adds measured encoder improvements and an opt-in smaller compressor.

Stream correctness and reuse

  • Drain decoded output before source refill in sync and async reads. Sync-flush compression before flushing the sink, including tiny buffers and async-only sinks.
  • Release caller arrays after operations and source/buffer references on disposal. Correct CanWrite after completion and cancellation on empty/EOF reads.
  • Use a ValueTask read core and Memory-based source reads on modern targets while preserving the Task API.
  • Allocate dynamic tables lazily and reuse decoders, code lengths and tree-building scratch across blocks.
  • Add ZStream.deflateReset/inflateReset and ZOutputStream.Reset. The wrapper requires a successfully finished stream and reuses its codec and output buffer for separately framed independent messages.
  • Cache at most four cleared default compressor buffer bundles: 1 MiB of array payload. Custom memory/window settings bypass this cache, and cache misses allocate normally.
  • Reuse encoder code-generation scratch; fresh/reset output remains byte-identical for the same options and write pattern.

Additional performance changes

Each change has a focused commit and regression coverage or an existing regression suite covering the affected behavior:

  • Bulk-clear compressor hash tables on reset/full flush instead of clearing 32,768 entries individually.
  • Use the .NET 8 trailing-zero intrinsic for word-match differences, retaining the portable fallback. Test every mismatch byte/bit across eight unaligned offsets.
  • Build Huffman entries with scalar stores and remove redundant scratch clearing and the temporary entry array.
  • Feed modern compression Span input directly into the codec window. A call-scoped ref struct never enters persistent state or crosses an await. Passing it by readonly reference avoids a repetitive-data regression found in the first prototype. Array APIs and older targets remain supported; Span decompression still stages through a bounded pooled array.
  • Cache one cleared default decoder window and one lazy Huffman table, bounded to 50,048 bytes of additional idle payload. Concurrent decoders own separate leases; custom windows bypass the window cache.
  • Expose memory levels 1-9 through ZStream.deflateInit(level, bits, memoryLevel) and the five-argument compression ZOutputStream constructor. Memory level 6 reduces the four main buffers from 256 KiB to 160 KiB while retaining 32 KiB history. It is opt-in: incompressible data can become substantially slower and compressed size can increase.
  • Remove the old port's unconditional early block-truncation heuristic. Native zlib 1.1.3 gated it behind TRUNCATE_BLOCK; it is absent in 1.3.1. The mixed 1 MiB fixture shrinks from 363,985 to 363,321 bytes. Three mixed-data golden outputs at levels 4/6/9 deliberately change to smaller encodings; the other golden outputs remain pinned and platform-validated.

The prior Ubuntu allocation test failure was fixed by warming additional calls and comparing three measurement batches. Recurring per-message allocations still fail the test; one-time runtime initialization does not count as codec scratch.

Measurements and rejected experiments

The additional experiment report contains all 54 cases, three baseline/final runs, allocation counts, compressed sizes/hashes, raw data, a later baseline control, and reproducible rejected patches. These compare against the previous PR head bf13e1d. The earlier report separately compares the initial changes against v2.0.2; percentages are not cumulative.

Windows ARM64, .NET 8.0.28, Release, memory-backed I/O:

Case, compared with previous PR head Before After
Dynamic reader, warmed allocation/stream 62,040 B 11,896 B (-80.8%)
Stored reader, warmed allocation/stream 41,616 B 8,824 B (-78.8%)
Main buffers, memory level 8 versus opt-in 6 256 KiB 160 KiB (-37.5%)
Reused empty compression 0.0086 ms 0.0010 ms (-88.6%)
Reused 2 KiB compression 0.0218 ms 0.0132 ms (-39.6%)
Many-block text reader, 4 KiB reads 1.4668 ms 1.2677 ms (-13.6%)
1 MiB random Span write, compression level 0 0.2684 ms 0.2355 ms (-12.3%)

Large-data CPU results are mixed. The full-suite low-level level-0 cases measured about 11-12% slower, while isolated level-0 processes reverse that result. A subsequent baseline control also showed significant host variability. The report includes these results and small regressions; it does not claim universal CPU gains. Allocation counts, buffer-size reductions and the reviewed compressed-size change are more robust conclusions.

Stackalloc for all small Huffman scratch, stackalloc for only the value workspace, direct stored-block output, and an array copy/checksum specialization were prototyped and rejected because timing did not justify retaining them. Full raw/wrapped engine duplication and wrapper-buffer rental were analyzed without adopting them; the wrapper's protected arrays complicate safe shared ownership. Flush batching is measured as a caller-controlled latency/size tradeoff; explicit Flush still exposes each message immediately.

Warm allocation savings do not equal lower peak resident memory: caches retain cleared arrays, and cold or highly concurrent streams can allocate full buffers. Explicit Reset retains its codec until disposal and requires callers to frame independent messages. The package version is unchanged; no release or publication is included.

Validation

  • net8.0 library: 320 tests.
  • netstandard2.1 library on .NET 8: 320 tests.
  • netstandard2.0 library on .NET 8: 277 tests.
  • netstandard2.0 library on .NET Framework 4.8: 258 tests.
  • Fuzz replay: 37 inflate and 36 fresh/reset roundtrip inputs.
  • Release package/symbol creation and benchmark builds.
  • Memory-level, stack-backed/sliced Span, flush, retention, dictionary/history, checksum, concurrency, entropy-transition and reviewed golden-output coverage.
  • Markdown lint and git diff --check. Unified-diff artifacts preserve legacy context whitespace as data; source checks remain enabled.
  • Ubuntu, Windows and macOS test jobs, packaging, and Codacy all passed on final head 9aa46af; GitHub reports the PR merge state as clean. No sustained fuzz campaign or x64 benchmark was run locally.

@jogibear9988 jogibear9988 changed the title Fix stream latency and reduce codec allocations with safe reuse Fix stream latency and reduce codec allocations with measured performance improvements Nov 1, 2026
@cinderblocks
cinderblocks merged commit 2576166 into cinderblocks:master Nov 3, 2026
6 checks passed
@jogibear9988
jogibear9988 deleted the perf/stream-memory-and-reuse branch November 3, 2026 05:37
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.

2 participants