Shrinking .wasm Size - Rust and WebAssembly (original) (raw)

  1. 1. Introduction
  2. 2. Why Rust and WebAssembly?
  3. 3. Background And Concepts
    1. 3.1. What is WebAssembly?
  4. 4. Tutorial
    1. 4.1. Setup
    2. 4.2. Hello, World!
    3. 4.3. Rules
    4. 4.4. Implementing Life
    5. 4.5. Testing Life
    6. 4.6. Debugging
    7. 4.7. Adding Interactivity
    8. 4.8. Time Profiling
    9. 4.9. Shrinking .wasm Size
    10. 4.10. Publishing to npm
  5. 5. Reference
    1. 5.1. Crates You Should Know
    2. 5.2. Tools You Should Know
    3. 5.3. Project Templates
    4. 5.4. Debugging
    5. 5.5. Time Profiling
    6. 5.6. Shrinking .wasm Size
    7. 5.7. JavaScript Interoperation
    8. 5.8. Which Crates Will Work Off-the-Shelf with WebAssembly?
    9. 5.9. How to Add WebAssembly Support to a General-Purpose Crate
    10. 5.10. Deploying Rust and WebAssembly to Production

Rust and WebAssembly

Shrinking .wasm Size

For .wasm binaries that we ship to clients over the network, such as our Game of Life Web application, we want to keep an eye on code size. The smaller our.wasm is, the faster our page loads get, and the happier our users are.

How small can we get our Game of Life .wasm binary via build configuration?

Take a moment to review the build configuration options we can tweak to get smaller .wasm code sizes.

With the default release build configuration (without debug symbols), our WebAssembly binary is 29,410 bytes:

$ wc -c pkg/wasm_game_of_life_bg.wasm
29410 pkg/wasm_game_of_life_bg.wasm

After enabling LTO, setting opt-level = "z", and running wasm-opt -Oz, the resulting .wasm binary shrinks to only 17,317 bytes:

$ wc -c pkg/wasm_game_of_life_bg.wasm
17317 pkg/wasm_game_of_life_bg.wasm

And if we compress it with gzip (which nearly every HTTP server does) we get down to a measly 9,045 bytes!

$ gzip -9 < pkg/wasm_game_of_life_bg.wasm | wc -c
9045

Exercises

[features]  
default = ["wee_alloc"]  

How much size does using wee_alloc shave off of the .wasmbinary?