skip to content

A Rust image filter's `.wasm` stays near 19 KB with `opt-level = "z"`, `lto` and `strip`, though its one export is a few lines; what is taking the space, and how do you shrink it?

level: seniorimportance: should knowfreq 28%

answer

  1. not your loop
  2. every reachable panic formats
  3. core::fmt plus the panic runtime
  4. wasm targets already abort
  5. wasm-opt after rustc

basics

~20 s

Reachable panics: any unwrap() keeps std's panic runtime and core::fmt alive. Replacing two with let-else and unwrap_or cut a measured build from 19,281 to 1,131 bytes; panic = "abort" changed nothing, as wasm targets already abort. Then run wasm-opt.

solid answer

~40 s

The filter's own code is tiny; the bulk is what any reachable panic drags in: the panic entry point, the hook machinery and `core::fmt` to format the message and location. In a measured `wasm32-unknown-unknown` build the strict version, with two `unwrap()` calls, was 19,281 bytes under `opt-level = "z"`, `lto = true`, `codegen-units = 1` and `strip = true`; replacing them with let-else and `unwrap_or` made it 1,131 bytes. Adding `panic = "abort"` changed nothing, because wasm targets are compiled with `-C panic=abort` already. So: remove panic paths from exported code, avoid `format!` and `Debug` there, keep the size profile, compare `"s"` with `"z"`, and finish with `wasm-opt`, which a `wasm-pack build` release runs with `-O` by default and can be set to `-Oz`.

code

rust · 18 lines
rust
/// Parses the filter strength the page sends as UTF-8 text, such as "40".
#[unsafe(no_mangle)]
pub extern "C" fn strength(ptr: *const u8, len: usize) -> u8 {
    // SAFETY: the page wrote `len` bytes at `ptr` in this module's memory.
    let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };

    #[cfg(feature = "strict")]
    {
        // Two reachable panics: each pulls in core::fmt and std's panic runtime.
        core::str::from_utf8(bytes).unwrap().parse::<u8>().unwrap()
    }
    #[cfg(not(feature = "strict"))]
    {
        // No reachable panic: a bad input becomes strength 0.
        let Ok(text) = core::str::from_utf8(bytes) else { return 0 };
        text.parse::<u8>().unwrap_or(0)
    }
}

go deeper

for a junior

Recall that a release build, size-focused optimisation and wasm-opt all shrink a .wasm, and that panics and formatting code are a large part of a small module.

for a middle

Explain why one unwrap keeps the panic runtime and core::fmt alive, and what lto, codegen-units, opt-level and strip each change.

for a senior

Demonstrate a measured diagnosis: compare builds one change at a time, know that wasm targets already abort on panic, remove panic paths from exports, and measure after wasm-opt.

for a principal

Turn size into a guarded budget: a review rule against panics and formatting in exported code, and a CI size report on the shipped module.

## Measure before changing anything Size work on WebAssembly goes wrong when people tune flags without measuring. A useful loop: 1. Build release for the target and record the byte size of the `.wasm`. 2. Change one thing. 3. Rebuild and compare, ideally on the file the page actually downloads (after the wasm-bindgen CLI and `wasm-opt`). The numbers below come from one small exported function, `strength`, which parses a filter strength such as "40" from UTF-8 bytes. Its `strict` variant calls `unwrap()` twice; the default variant handles bad input without panicking. | Build of the `strength` crate | strict (two `unwrap()`) | no reachable panic | |---|---|---| | default release profile | 28,498 bytes | 1,756 bytes | | `opt-level = "z"`, `lto = true`, `codegen-units = 1`, `strip = true` | 19,281 bytes | 1,131 bytes | | same, plus `panic = "abort"` | 19,281 bytes | not measured | | same, with `opt-level = "s"` | 19,309 bytes | 1,145 bytes | ## Where the bytes go: panics and formatting A **panic** needs more than a jump: std's panic machinery records the location, runs the panic hook, and formats the message with `core::fmt`, whose code paths for arguments and padding are large relative to a small filter. One reachable `unwrap()` keeps all of that alive; removing every reachable panic lets the linker drop it. That is why the strict variant stays near 19 KB under the size profile while the panic-free one falls to about 1 KB. Sources of hidden panics: - `unwrap()` and `expect()` on `Option` and `Result`; - slice indexing that the optimiser cannot prove in bounds; - `format!`, `to_string()` and `{:?}` in exported code, which pull in `core::fmt` even without a panic; - `assert!` with a formatted message. Rewrites that remove them: let-else returning a neutral value, `unwrap_or` and `unwrap_or_default`, `get()` instead of indexing, and returning a `Result` to JavaScript where the caller can handle the error. ## Why `panic = "abort"` does not help here On native targets, `panic = "abort"` drops unwinding tables. Rust's wasm targets are already compiled with `-C panic=abort`: `rustc --print cfg --target wasm32-unknown-unknown` shows `panic="abort"`, and the prebuilt std for these targets aborts. The measured build stayed at 19,281 bytes with the setting. The cost of a panic on wasm is the formatting and hook machinery, not unwinding. ## Profile settings, measured The profile keys belong to Cargo's profiles material; what matters here is their effect on a `.wasm`: - `opt-level = "z"` or `"s"`: optimise for size; Cargo's docs warn that neither is always smaller, and here they differed by 14 to 28 bytes; - `lto = true` with `codegen-units = 1`: whole-program optimisation, which lets unused std code go; - `strip = true`: removed the `name`, `producers` and `target_features` custom sections, 24,141 down to 19,281 bytes in the strict build. wasm-bindgen's own `__wasm_bindgen_unstable` section survived it, so the CLI still works. ## After rustc: wasm-opt and the glue **wasm-opt**, from Binaryen, optimises the finished module. `wasm-pack build` runs it in the release and profiling profiles with `-O` by default; `[package.metadata.wasm-pack.profile.release]` takes `wasm-opt = ["-Oz"]` for a size-first pass, and `--no-opt` skips it. Measure the output of this step, since it is what ships. Other contributors worth checking once panics are gone: - the default global allocator on `wasm32-unknown-unknown` is dlmalloc, which the linker can leave out of code that never allocates; - generic code monomorphised for many types multiplies, which is generics material; - every `#[wasm_bindgen]` export adds glue on both sides. ## Looking inside the module When a build is still larger than expected, inspect it rather than guess: - list the **custom sections** and their sizes; here `name` alone was 4,622 bytes before `strip`; - list the **exports**: a `cdylib` built without wasm-bindgen should export little more than `memory` and your functions; - search the data section for panic message text and source paths, which betray a reachable panic; - compare the file before and after the wasm-bindgen CLI and `wasm-opt`, since the shipped file is the one that counts. ## A team rule that keeps it small Panics in exported code become a review item: exported functions return `Result` or a neutral value, and a CI step records the shipped `.wasm` size so a new `unwrap()` that adds kilobytes shows up in the pull request.

  • Why does adding `panic = "abort"` not shrink this WebAssembly build?
    Rust's wasm targets already compile with `-C panic=abort`, so there are no unwinding tables to remove; `rustc --print cfg` for the target shows `panic="abort"`. In the measured build the size stayed at 19,281 bytes. What a panic costs on wasm is the hook and message-formatting code, which only removing the panic paths eliminates.
  • Where does wasm-opt fit, and how do you set its level with wasm-pack?
    wasm-opt runs on the finished module, after rustc and the wasm-bindgen CLI. `wasm-pack build` runs it with `-O` in the release and profiling profiles by default, finding it on PATH or downloading it. Set `wasm-opt = ["-Oz"]` under `[package.metadata.wasm-pack.profile.release]` for a size-first pass, or pass `--no-opt` to skip it.
  • Is `opt-level = "z"` always smaller than `"s"` for a wasm build?
    No. Cargo's documentation warns that neither size level is guaranteed to be smaller, and recommends measuring. In this crate `"z"` won by 28 bytes with panics and 14 without, which is noise next to the 18 KB that removing two `unwrap()` calls saved. Pick by measurement, then spend effort on panic paths and formatting.

  • `panic = "abort"` is the big size win on wasm because it removes unwinding.
  • `opt-level = "z"` always produces the smallest WebAssembly binary.
  • A default release build already strips symbol names, so `strip = true` changes nothing.
  • Most of the size is the filter loop, so the loop should be rewritten.
  • An `unwrap()` that never fails at run time costs nothing in the binary.