c35660.org
「Optimizing Pure Rust Zstd in WebAssembly to 89% of Emscripten Without Unsafe」の c35660.org です。「そのまま開く」はファイルをそのまま返します。
* Optimizing Pure Rust Zstd in WebAssembly to 89% of Emscripten Without Unsafe
:properties:
:export_file_name: generated/contents/blog/2026/c35660
:export_date: 2026-12-04 22:47
:export_updated: 2026-12-04 22:47
:export_lang: en
:export_original: /blog/2026/315c2e
:export_tags: rust webassembly performance differential-testing zstd-rs
:end:
For Shiguredo's Pure Rust Zstandard library [[https://github.com/shiguredo/zstd-rs][shiguredo/zstd-rs]], I assembled an optimization proposal in [[https://github.com/conao3/zstd-rs/tree/feature/optimize-wasm-perf][conao3/zstd-rs commit 92aa3fc]] that speeds up WebAssembly compression by 52.6%, speeds up decompression by 70.7%, and cuts standalone linear memory by 52.0% while keeping =#![forbid(unsafe_code)]=, =#![no_std]=, and zero dependencies.
Even in safe Rust, reshaping loops and data structures around V8 TurboFan register limits and WebAssembly linear memory layout, then cutting harmful ideas through measured ablations, brings speed close to the official C Emscripten build with lower memory usage.
The companion post [[/blog/2026/c947fe][on the development workflow]] describes how I coordinated local and web AI agents to build this proposal without editing code by hand.
From the maintainer side, voluntas wrote [[https://voluntas.ghost.io/rapid-zstd-rs/][zstd-rs に性能改善提案をいただいて約 2 倍早くなった]] (in Japanese), covering Shiguredo's benchmark setup and review process.
[[github:shiguredo/zstd-rs::Rust][Zstandard (RFC 8878) Library]]
** Constraints and benchmark results
Baseline measurements used =shiguredo/zstd-rs= commit =3894aa1=, and the proposal kept all six constraints intact:
- Keep =#![forbid(unsafe_code)]= with no unsafe blocks or raw pointer arithmetic.
- Run under =#![no_std]= plus =alloc= with zero external runtime crate dependencies.
- Keep MSRV at Rust 1.95 and preserve public API compatibility.
- Avoid DoS vulnerabilities from trusting input-header sizes in =Vec::with_capacity=.
- Preserve or improve the compression ratio.
- Back all changes with Chromium WebAssembly benchmarks.
We ran interleaved measurements on local NixOS with an Intel Core i5-8400, Chromium 158, Rust 1.100.1 targeting =wasm32-unknown-unknown=, and =wasm-opt -O3=, using six files from the Silesia compression corpus totaling 46,855,742 bytes.
[[./resources/public/img/c35660-benchmark.svg]]
| Metric | Baseline 3894aa1 | Proposal 92aa3fc | Change | Emscripten Level 1 | ruzstd |
|---+----+----+----+----+----|
| Compression speed | 124.8 MiB/s | 190.4 MiB/s | +52.6% | 223.3 MiB/s | 51.2 MiB/s |
| Decompression speed | 279.4 MiB/s | 476.9 MiB/s | +70.7% | 537.1 MiB/s | 196.8 MiB/s |
| Total compressed size | 15,764,178 B | 15,727,940 B | -36,238 B | 17,116,627 B | - |
| Compression ratio | 0.336441 | 0.335667 | Smaller on all 6 files | 0.365 | 0.442 |
| Standalone wasm size | 93,642 B | 99,731 B | +6,089 B | - | - |
| Standalone linear memory (post-decode) | 144.063 MiB | 69.188 MiB | -52.0% | 107.563 MiB | 139.938 MiB |
Per-file results also improved speed and shrank output size across all six files.
| File | Compression Base→Proposal | Decompression Base→Proposal | Compressed size delta |
|---+----+----+----|
| dickens | 84.9 → 116.7 MiB/s | 184.6 → 369.6 MiB/s | -945 B |
| xml | 218.8 → 326.8 MiB/s | 396.8 → 610.6 MiB/s | -349 B |
| ooffice | 73.1 → 127.3 MiB/s | 204.8 → 314.6 MiB/s | -14,177 B |
| nci | 270.8 → 388.4 MiB/s | 406.2 → 629.9 MiB/s | -595 B |
| mozilla | 130.6 → 223.8 MiB/s | 342.6 → 536.9 MiB/s | -19,789 B |
| samba | 162.2 → 240.2 MiB/s | 323.3 → 540.6 MiB/s | -383 B |
Upstream [[https://github.com/shiguredo/zstd-rs/commit/2b5fd0b35ee8efe2326347b994b2e42b8a60cbf7][commit 2b5fd0b35e]] combines proposals from cp-20 and serinuntius with adjustments by voluntas, reaching 201.7 MiB/s compression, 447.7 MiB/s decompression, and 63.375 MiB linear memory after aggregate decoding on GitHub Actions.
All remaining numbers below come from local Chromium benchmarks and ablations on proposal branch =92aa3fc=.
** Changes that raised decompression speed by 70.7%
Zstandard decompression splits into three stages: Huffman decoding of literals, FSE state transitions for lengths and offsets, and copying bytes into the output buffer.
Measuring about 1.97 million sequences in common frames showed that all of them fit inside 57 total bits per sequence, and 80.8% had copy lengths of 16 bytes or less.
Guided by that distribution, we made four decoder changes tailored to V8 TurboFan code generation.
*** Two-phase batch decoding in 64-sequence chunks
Splitting sequence bit decoding and output copying into two phases of 64 sequences delivered the largest speedup.
[[./resources/public/img/c35660-decode-batch.svg]]
Holding three FSE states, the bit reader cursor, three repeat-offset variables, and literal and output cursors in one loop created too many live values, so V8 TurboFan spilled the FSE states and bit position onto the stack.
That forced the cross-sequence dependency chain through memory on each iteration and capped throughput.
We split the loop into =decode_batch=, which unpacks 64 sequences from the bitstream into a stack array, and =execute_batch=, which reads that array and writes to the output buffer.
Narrowing loop-carried values in phase one to three FSE states and the bit position let V8 keep those hot variables in registers.
*** 16-byte unified table and branchless 57-bit extraction
We merged the three FSE decode tables (literal length, match length, and offset) into one reusable buffer owned by the decoder.
This removes per-block heap allocations and validates symbol bounds and next-state ranges at table-build time, removing error branches from the hot loop.
We also padded each entry to 16 bytes and aligned masks and bit-width fields to byte boundaries.
Bit extraction then takes one rotate-left and one mask AND, and normal sequences under 57 bits fetch all three final state updates in one shot.
*** Fixed-width copy paths and outer-loop capacity growth
Calling variable-length =copy_from_slice= on short WebAssembly copies exposes =memory.copy= call overhead.
Because over 80% of sequences copy 16 bytes or less, we added 8-byte, 16-byte, and 32-byte fixed-width copy paths for both literals and matches.
For overlapping matches where distance is shorter than copy length, the decoder doubles the prefix in 1x, 2x, and 4x steps.
For raw uncompressed literals, it reads from the input slice with no intermediate copy, and outer-loop =Vec= growth reduces bounds checks inside the hot loop.
*** 2-wide X2 and 4-wide X1 Huffman decoding
Four-stream Zstandard Huffman decoding switches between an X2 table that emits two symbols per lookup and an X1 path that emits one symbol at a time.
On blocks rich in short codes, 2-wide X2 decoding sums consumed bits and output offsets in batches and writes four steps as a =u64=.
The X1 path keeps four parallel streams, plants a sentinel bit at the bottom of a 64-bit window to count consumed bits via trailing zeros, and decodes FSE-compressed Huffman weights in a stack array with no per-block heap allocation.
** Changes that raised compression speed by 52.6% and improved ratio
A V8 CPU profile showed that history match search took about 70% of compression time.
We paired techniques that cut random memory reads during search with cleaner entropy coding.
*** 8-bit inline tags and NUL-ratio hash width switching
We stored the top 8 bits of the 7-byte hash product as an inline tag in the high byte of each history-table slot.
Checking that tag filters out colliding slots on lookup and cuts random reads into the input buffer by 71%.
We also simplified table clearing to zero-initialization and checked repeat-offset positions ahead of hash candidates, adding a standalone 2.6% speedup.
Sampling up to 256 positions from the frame start lets the encoder switch the hash key width from 56 bits to 52 bits on binary-leaning inputs with 8 or more NUL bytes.
Picking the multiplier once at frame start adds zero instructions inside the search loop while shrinking compressed output by 33,137 bytes at full speed.
*** Entropy coding and keeping wasm size under 100 KB
Precomputing the output bit-width adjustment =delta_nb_bits= inside the FSE transition table added 2.0% compression speed on its own, and writing the bitstream in 8-byte chunks into a forward slice added 0.9%.
To balance speed and ratio, the encoder compares costs across RLE literals, Treeless Huffman, and FSE Repeat, and redistributes leaf counts whenever a block's Huffman tree exceeds the depth limit.
Replacing standard =sort= on small arrays with insertion sort and shell sort trimmed generic monomorphization and kept the standalone =.wasm= binary at 99,731 bytes, under 100 KB.
Switching =xxh64= checksumming to =chunks_exact(32)= also cut bounds checks.
** Optimization ideas rejected by measured ablations
V8 TurboFan and WebAssembly's linear memory allocator behave in ways that differ from native targets, so several plausible optimizations regressed when measured.
| Tested idea | Goal | Measured result and rejection reason |
|---+----+----|
| 1-stream sequential Huffman decode | Lower TurboFan register pressure | Lost instruction-level parallelism; decode fell from 427.7 to 395.1 MiB/s |
| Direct write to compressed block output | Drop intermediate =BlockScratch= | Broke linear memory layout; post-decode memory doubled from 69.188 to 142.250 MiB |
| Pre-allocating scratch buffers | Cut repeated reallocations | Changed dlmalloc growth layout; standalone linear memory jumped to 135.688 MiB |
| Skipping long-distance 4-byte matches | Drop weak short matches | Matches of length 6 or less were 0.0% on the 7-byte hash path |
| 12-byte sequence struct and Repeat borrowing | Shrink structs and copies | Standalone ablations regressed by -0.4% to -0.6% |
In WebAssembly linear memory, growing a buffer with no free space right behind it copies the whole output elsewhere before expanding.
Small shifts in intermediate buffer lifetime or allocation order can spike peak memory by almost 70 MiB, so pairing speed runs with =memory.spec.ts= proved essential.
** Safety verification and remaining gaps
Adding fast paths invites edge-case bugs.
During independent review, Claude Fable 5.2 caught a panic in =init_guess.clamp(256, block_max)= on single-segment frames smaller than 256 bytes, replaced it with =max(256).min(block_max)=, and added regression tests from 1 to 600 bytes.
For final validation, GPT-6.2 Astra ran 87,228 mutated-frame differential decoder tests and 1,747 post-error decoder reuse tests, with zero output mismatches, zero error-kind mismatches, and zero panics.
Compressed outputs also matched byte for byte between native and WebAssembly across all six Silesia files.
Because differential testing compared outputs against the prior generation, it could not catch shared assumptions inherited from the earlier code.
After I shared the branch, voluntas's fuzzing pass found an integer underflow in the proposal's [[https://github.com/conao3/zstd-rs/blob/92aa3fc21f6517d23e6df5f8de3d60563afa3f6e/src/decoder.rs#L1421-L1532][decoder path]].
Given a non-canonical 2-byte =Number_of_Sequences= starting with =0x80= followed by =0x00=, the decoder skipped the ~byte0 == 0~ early return and reached =nb_sequences - 1= while =nb_sequences= was still 0.
Standard encoders emit 0 as the single byte =0x00=, so mutating valid frames missed that boundary.
Upstream commit =2b5fd0b35e= pulled in cp-20's fix, computing =nb_sequences= first and then checking for 0.
On the final V8 CPU profile, the sequence fast path takes 43.6% of decode time, while the JavaScript =decompress= wrapper and =wasm-bindgen= I/O copies take 23.8%.
On the compression side, 71.2% of self-samples sit in history match search.
Reaching 0.85x of the Emscripten build in compression and 0.89x in decompression while paying =wasm-bindgen= boundary copies means the Pure Rust core runs close to the C implementation.
** Closing
Under =#![forbid(unsafe_code)]= and =#![no_std]=, measuring the input distribution, splitting loops to fit V8 TurboFan registers, and keeping only ablations that preserve WebAssembly linear memory layout raised compression speed by 52.6% and decompression speed by 70.7%.
The companion post [[/blog/2026/c947fe][on agent collaboration]] covers how I drove this optimization by pairing local and web AI models without writing a single line of code.