slimwasm 0.1.0

A WASM size profiler for wasm32-unknown-unknown and wasm32-wasip2 binaries
Documentation

slimwasm

CI License

A WASM size profiler for wasm32-unknown-unknown and wasm32-wasip2 binaries.

slimwasm helps you answer: "Why is this .wasm 1.2 MB and who retains core::fmt?"

A spiritual successor to the archived twiggy project. Unlike cargo-bloat which is native-only, slimwasm is designed specifically for WebAssembly.

Installation

cargo install --git https://github.com/Thomas-E-Lewis/slimwasm

Or build from source:

git clone https://github.com/Thomas-E-Lewis/slimwasm

cd slimwasm

cargo install --path .

Commands

slimwasm top - Show Largest Items

Display the largest items in a .wasm file, ranked by size:

slimwasm top my_app.wasm

slimwasm top my_app.wasm -n 30           # Show top 30 items

slimwasm top my_app.wasm --retained      # Show retained size (item + everything it keeps alive)

slimwasm top my_app.wasm --json          # Output as JSON

Example output:

 my_app.wasm - 156.5 KiB 

Sections:
     89.2 KiB   57.0%  code
     45.3 KiB   28.9%  data
     12.1 KiB    7.7%  custom:name
      5.2 KiB    3.3%  type

Shallow Size (top 20):
     12.3 KiB    7.9%  [function]  core::fmt::write
      8.7 KiB    5.6%  [function]  core::fmt::Formatter::pad
      6.2 KiB    4.0%  [function]  <&T as core::fmt::Display>::fmt
      ...

slimwasm why - Explain Item Retention

Find out why a specific item is included in your binary:

slimwasm why my_app.wasm "core::fmt"

slimwasm why my_app.wasm "panic" --depth 15

slimwasm why my_app.wasm "alloc::string" --json

Example output:

 Why is 'core::fmt' in the binary? 

Matching items:
  -> core::fmt::write (12.3 KiB)
  -> core::fmt::Formatter::pad (8.7 KiB)

Retention paths (who keeps this alive):

  Path 1 to 'core::fmt::write':
    └─> my_app::render_error (calls next)
        └─> my_app::handle_request (calls next)
            └─> _start

Tip: To reduce size, consider removing or replacing the root callers.

slimwasm diff - Compare Two Binaries

See what changed between two versions of your WASM:

slimwasm diff old.wasm new.wasm

slimwasm diff old.wasm new.wasm -n 50    # Show more items

slimwasm diff old.wasm new.wasm --json   # Output as JSON

Example output:

 WASM Size Diff 

  Old: old.wasm (145.2 KiB)
  New: new.wasm (156.5 KiB)

  Total: 145.2 KiB -> 156.5 KiB (+11.3 KiB / +7.8%)

Changes:

  Added (3):
    + 8.2 KiB  [function]  new_feature::process
    + 2.1 KiB  [function]  new_feature::validate
    + 1.0 KiB  [data]      data[42]

  Removed (1):
    - 512 B    [function]  deprecated_func

  Changed (5):
    ↑ +2.3 KiB  [function]  main_handler
    ↓ -128 B    [function]  utility_fn

slimwasm exports - Component Export Sizes

Dump export information for WASM Component Model binaries (wasm32-wasip2/WIT):

slimwasm exports my_component.wasm

slimwasm exports my_component.wasm --json

Real-World Demo: Killing core::fmt Bloat

One of the most common sources of WASM bloat is formatting machinery from core::fmt. Here's a step-by-step demo showing how to identify and eliminate it.

Step 1: Create a "Fat" WASM Binary

Create a new project:

cargo new --lib wasm-demo

cd wasm-demo

Add to Cargo.toml:

[lib]

crate-type = ["cdylib"]



[dependencies]

wasm-bindgen = "0.2"



[profile.release]

opt-level = "z"

lto = true

Create src/lib.rs with formatting-heavy code:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}! The answer is {}", name, 42)
}

#[wasm_bindgen]
pub fn process_data(data: &[u8]) -> Result<String, JsValue> {
    if data.is_empty() {
        return Err(JsValue::from_str(&format!("Error: empty data")));
    }
    Ok(format!("Processed {} bytes", data.len()))
}

Build:

cargo install wasm-bindgen-cli

cargo build --release --target wasm32-unknown-unknown

wasm-bindgen --target web --out-dir pkg target/wasm32-unknown-unknown/release/wasm_demo.wasm

Check the size:

ls -lh pkg/wasm_demo_bg.wasm

# => 47K pkg/wasm_demo_bg.wasm

Step 2: Analyze with slimwasm

slimwasm top pkg/wasm_demo_bg.wasm --retained

Output (abbreviated):

 wasm_demo_bg.wasm - 47.2 KiB 

Sections:
     38.1 KiB   80.7%  code
      4.2 KiB    8.9%  data
      3.1 KiB    6.6%  custom:name

Retained Size (top 20):
     12.8 KiB   27.1%  [function]  core::fmt::write
      9.2 KiB   19.5%  [function]  core::fmt::Formatter::pad
      4.1 KiB    8.7%  [function]  alloc::fmt::format::format_inner
      ...

Almost 50% of the binary is core::fmt machinery!

Find out why it's retained:

slimwasm why pkg/wasm_demo_bg.wasm "core::fmt::write"

Output:

Retention paths (who keeps this alive):

  Path 1 to 'core::fmt::write':
    └─> alloc::fmt::format::format_inner (calls next)
        └─> wasm_demo::greet (calls next)
            └─> export:greet

The format! macro in greet() pulls in all the formatting machinery.

Step 3: Create a "Slim" Version

Create src/lib.rs without format!:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    let mut result = String::with_capacity(name.len() + 30);
    result.push_str("Hello, ");
    result.push_str(name);
    result.push_str("! The answer is 42");
    result
}

#[wasm_bindgen]
pub fn process_data(data: &[u8]) -> Result<String, JsValue> {
    if data.is_empty() {
        return Err(JsValue::from_str("Error: empty data"));
    }
    let mut result = String::from("Processed ");
    // Convert length to string without format!
    let len = data.len();
    let mut digits = Vec::new();
    let mut n = len;
    if n == 0 {
        digits.push(b'0');
    }
    while n > 0 {
        digits.push(b'0' + (n % 10) as u8);
        n /= 10;
    }
    digits.reverse();
    result.push_str(core::str::from_utf8(&digits).unwrap());
    result.push_str(" bytes");
    Ok(result)
}

Or even simpler, use itoa crate for number-to-string conversion without core::fmt.

Rebuild:

cargo build --release --target wasm32-unknown-unknown

wasm-bindgen --target web --out-dir pkg target/wasm32-unknown-unknown/release/wasm_demo.wasm

Step 4: Compare Results

slimwasm diff pkg/wasm_demo_bg.wasm.bak pkg/wasm_demo_bg.wasm

Results:

  Total: 47.2 KiB -> 12.1 KiB (-35.1 KiB / -74.4%)

  Removed (25):
    - 12.8 KiB  [function]  core::fmt::write
    - 9.2 KiB   [function]  core::fmt::Formatter::pad
    - 4.1 KiB   [function]  alloc::fmt::format::format_inner
    ...

74% size reduction by eliminating core::fmt!

Additional Tips for WASM Size Reduction

  1. Use panic = "abort" in your release profile:

    [profile.release]
    
    panic = "abort"
    
    
  2. Enable LTO (Link-Time Optimization):

    [profile.release]
    
    lto = true
    
    
  3. Optimize for size:

    [profile.release]
    
    opt-level = "z"  # or "s"
    
    
  4. Strip debug info:

    [profile.release]
    
    strip = true
    
    
  5. Use wasm-opt from Binaryen:

    wasm-opt -Oz -o optimized.wasm input.wasm
    
    
  6. Avoid these common bloat sources:

    • format!(), println!(), panic!() with messages
    • Debug trait implementations
    • std::io::Error (pulls in formatting)
    • Stack unwinding (use panic = "abort")

How It Works

slimwasm parses WASM binaries using wasmparser and builds a call graph from the code section. It computes:

  1. Shallow size: The raw byte size of each function/item
  2. Retained size: Size of an item plus everything it uniquely keeps alive (via dominator analysis)
  3. Retention paths: The call chain from exports/roots to any given function

For Component Model binaries (wasm32-wasip2), it additionally parses component sections to show component-level exports.

License

MIT. See LICENSE-MIT.