| 1 |
# Small wasm files |
| 2 |
|
| 3 |
[View full source code][code] or [view the compiled example online][online] |
| 4 |
|
| 5 |
[online]: https://rustwasm.github.io/wasm-bindgen/exbuild/add/ |
| 6 |
[code]: https://github.com/rustwasm/wasm-bindgen/tree/master/examples/add |
| 7 |
|
| 8 |
One of `wasm-bindgen`'s core goals is a pay-only-for-what-you-use philosophy, so |
| 9 |
if we don't use much then we shouldn't be paying much! As a result |
| 10 |
`#[wasm_bindgen]` can generate super-small executables |
| 11 |
|
| 12 |
Currently this code... |
| 13 |
|
| 14 |
```rust |
| 15 |
{{#include ../../../examples/add/src/lib.rs}} |
| 16 |
``` |
| 17 |
|
| 18 |
generates a 710 byte wasm binary: |
| 19 |
|
| 20 |
``` |
| 21 |
$ ls -l add_bg.wasm |
| 22 |
-rw-rw-r-- 1 alex alex 710 Sep 19 17:32 add_bg.wasm |
| 23 |
``` |
| 24 |
|
| 25 |
If you run [wasm-opt], a C++ tool for optimize WebAssembly, you can make it |
| 26 |
even smaller too! |
| 27 |
|
| 28 |
``` |
| 29 |
$ wasm-opt -Os add_bg.wasm -o add.wasm |
| 30 |
$ ls -l add.wasm |
| 31 |
-rw-rw-r-- 1 alex alex 172 Sep 19 17:33 add.wasm |
| 32 |
``` |
| 33 |
|
| 34 |
And sure enough, using the [wasm2wat] tool it's quite small! |
| 35 |
|
| 36 |
``` |
| 37 |
$ wasm2wat add.wasm |
| 38 |
(module |
| 39 |
(type (;0;) (func (param i32 i32) (result i32))) |
| 40 |
(func (;0;) (type 0) (param i32 i32) (result i32) |
| 41 |
get_local 1 |
| 42 |
get_local 0 |
| 43 |
i32.add) |
| 44 |
(table (;0;) 1 1 anyfunc) |
| 45 |
(memory (;0;) 17) |
| 46 |
(global (;0;) i32 (i32.const 1049118)) |
| 47 |
(global (;1;) i32 (i32.const 1049118)) |
| 48 |
(export "memory" (memory 0)) |
| 49 |
(export "__indirect_function_table" (table 0)) |
| 50 |
(export "__heap_base" (global 0)) |
| 51 |
(export "__data_end" (global 1)) |
| 52 |
(export "add" (func 0)) |
| 53 |
(data (i32.const 1049096) "invalid malloc request")) |
| 54 |
``` |
| 55 |
|
| 56 |
Also don't forget to compile in release mode for the smallest binaries! For |
| 57 |
larger applications you'll likely also want to turn on LTO to generate the |
| 58 |
smallest binaries: |
| 59 |
|
| 60 |
```toml |
| 61 |
[profile.release] |
| 62 |
lto = true |
| 63 |
``` |
| 64 |
|
| 65 |
[wasm2wat]: https://github.com/webassembly/wabt |
| 66 |
[wasm-opt]: https://github.com/webassembly/binaryen |