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?¶
With the default release build configuration (without debug symbols), our WebAssembly binary is 29,410 bytes:
1 2 | |
After enabling LTO, setting opt-level = "z", and running wasm-opt -Oz, the resulting .wasm binary shrinks to only 17,317 bytes:
1 2 | |
And if we compress it with gzip (which nearly every HTTP server does) we get down to a measly 9,045 bytes!
1 2 | |
Exercises¶
-
Use the
wasm-sniptool to remove the panicking infrastructure functions from our Game of Life's.wasmbinary. How many bytes does it save? -
Build our Game of Life crate with and without
wee_allocas its global allocator. Therustwasm/wasm-pack-templatetemplate that we cloned to start this project has a "wee_alloc" cargo feature that you can enable by adding it to thedefaultkey in the[features]section ofwasm-game-of-life/Cargo.toml:
1 2 | |
How much size does using wee_alloc shave off of the .wasm binary?
- We only ever instantiate a single
Universe, so rather than providing a constructor, we can export operations that manipulate a singlestatic mutglobal instance. If this global instance also uses the double buffering technique discussed in earlier chapters, we can make those buffers also bestatic mutglobals. This removes all dynamic allocation from our Game of Life implementation, and we can make it a#![no_std]crate that doesn't include an allocator. How much size was removed from the.wasmby completely removing the allocator dependency?