Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Performance and Debugging

Binary Size and Optimization

Learn how WebAssembly binaries are laid out, why LEB128 keeps them small, and how wasm-opt, stripping, LTO, twiggy and Brotli compression shrink modules for faster page loads.

On the web, bytes are time. A user on a slow phone connection must download your module before anything runs, so a 4 MB module is a real cost even if the code inside is fast. WebAssembly was designed with this in mind: the binary format is compact, designed to be decoded in one fast pass, and compresses well. But a careless build can still produce an enormous file, usually because a library pulled in more than you expected.

This lesson looks inside the format to see why it is small, then covers the practical size-reduction toolbox: compiler flags, wasm-opt, stripping, finding what is big, and compression on the wire.

How a module is laid out

A .wasm file starts with an 8-byte header (the magic bytes \0asm and a version number) followed by sections. Each section is one byte of id, the payload size, and the payload. Common sections, in their required order:

Id Section Holds
0 Custom Optional extras such as name and debug info
1 Type Function signatures
2 Import What the host must provide
3 Function The signature index of every function
5 Memory Memory declarations
6 Global Global variables
7 Export What the module offers
10 Code The function bodies
11 Data Initial memory contents

Because the section sizes are written up front, an engine can skip or parallelize sections, and it can start compiling function bodies while the rest of the file is still downloading.

LEB128: small numbers in few bytes

Almost every number in the binary (sizes, indexes, counts, integer constants) is encoded in LEB128, a variable-length encoding. Each byte carries seven bits of the number and a high "continue" bit. Values under 128 take one byte, values under 16,384 take two, and so on. Since most indexes and sizes are small, most numbers cost a single byte.

Node.js Encode and decode LEB128

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same compactness shows up everywhere: a function call is one opcode byte plus a one-byte index, local.get 0 is two bytes, and the whole sum_to function from the Emscripten lesson fits in 71 bytes including the header.

Measuring a module and its compression

Compression on the wire matters more than raw size. The next example builds a module programmatically with 300 small exported functions (a stand-in for a library with many similar routines), checks that it is valid, then reports its size per section and how well gzip and Brotli shrink it. It uses a tiny builder you will meet again in The WebAssembly Toolchain.

Node.js Size per section, then gzip and Brotli

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Repeated structure compresses extremely well, and real modules are less regular, so expect about 30% to 50% of the original size with Brotli. This is why you should always enable compression for .wasm on your server or CDN. And it also means you should compare compressed sizes when deciding whether an optimization was worth it.

The size-reduction toolbox

Shrink the compile

Optimize for size -Os, -Oz, opt-level s or z.
LTO Link-time optimization drops dead code.
Avoid bloat Skip fmt, regex and iostream if you can.
Panic = abort No unwinding tables.

Compiler flags give the biggest win.

1 / 2

1. Compile for size. Use -Oz (or -Os) with Emscripten, opt-level = "z" with Rust. Turn on link-time optimization (-flto, lto = true) so unused functions across files can be removed.

2. Avoid heavyweight dependencies. In C++, <iostream> and exceptions add tens of kilobytes. In Rust, format!, regex and panic message formatting are common culprits. Prefer small, no_std-friendly crates and panic = "abort".

3. Run wasm-opt. Binaryen's optimizer rewrites the module: it inlines, removes dead code, merges identical functions and shortens encodings.

Terminal
wasm-opt -Oz --strip-debug input.wasm -o output.wasm
# add --enable-bulk-memory, --enable-simd etc. if your module uses those features

4. Strip what users do not need. Remove the name section and DWARF (wasm-strip, wasm-opt --strip-debug --strip-producers). Keep an unstripped copy for debugging crash reports.

5. Find the fat. twiggy top module.wasm lists functions by size, and twiggy dominators shows what removing one function would let you drop. A surprising core::fmt or std::io entry usually means an innocent println! or format! pulled in a lot of code.

6. Split and defer. If a feature is rarely used, put it in its own module and load it on demand (see Bundlers and Loading Strategies).

7. Compress. Serve with Brotli (or gzip) and correct caching headers: Content-Type: application/wasm and a long Cache-Control with a hashed file name.

What not to chase

Micro-optimizing the last 2% rarely pays. A 150 KB module compressed to 60 KB is fine for most pages; the real wins are avoiding a 3 MB dependency and loading the module lazily. Also remember that speed and size trade off: -O3 can inline aggressively and grow the file, while -Oz is smaller but sometimes slower. Measure both on the code that matters (see WebAssembly Performance).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are most numbers in a .wasm binary only one byte?

    LEB128 stores seven bits per byte plus a continuation bit, so values below 128 fit in one byte.
  2. 2. Which sizes should you compare to judge the network cost of a module?

    Servers send compressed bytes. Wasm compresses well, so the compressed size is what users actually download.
  3. 3. What does wasm-opt -Oz do?

    wasm-opt is the optimizer from the Binaryen toolkit. -Oz asks for the smallest output.
  4. 4. What is a common reason a small Rust module becomes huge?

    Formatting machinery and large crates add a lot of code. twiggy helps you find where the bytes went.

Summary

  • A module is a header plus sections; sizes and indexes are LEB128-encoded, so the format is compact and quick to decode.
  • Compile for size (-Oz, opt-level = "z", LTO, panic = "abort"), avoid heavy dependencies, then run wasm-opt and strip debug data.
  • Use twiggy to find large functions.
  • Serve with Brotli or gzip, the right MIME type and long-lived caching; judge by compressed size.
  • Balance size against speed, and load rarely used code lazily.

Next: SIMD and Threads