Sikau

WebAssembly · Day 12 · about 50 min

Capstone: Fast across the boundary

Batch data into memory, grow it when needed, and learn when wasm really pays off.

Faster is not automatic

Many people expect that rewriting JavaScript in WebAssembly makes it faster. Sometimes it does, by a large factor: image filters, video codecs, physics, compression and cryptography all gain a lot. Sometimes it makes things slower, because the program spends its time crossing between the two worlds, or copying data back and forth.

Think of a chiya stall that serves from two kitchens across a road. One cup per trip is hopeless. A tray of twenty cups per trip is fine. Wasm is the same: the work inside each kitchen is quick, the crossing is the expensive part.

Compiling real languages to wasm

You wrote your own compiler earlier, but most wasm in the world comes from existing languages. A toolchain takes C, C++, Rust or Go and produces a .wasm file plus glue code. Emscripten compiles C and C++ and ships a JavaScript loader. Rust uses wasm-pack and wasm-bindgen to generate typed bindings for strings and objects. wasm-opt from Binaryen then shrinks and speeds up the output.

  • Source (C, Rust…) → compiler (Clang/LLVM, rustc) → .wasm.
  • Binaryen's wasm-opt removes dead code and tightens instructions.
  • The glue copies strings and arrays through linear memory, exactly as you wrote in the memory lesson.
  • Servers should send .wasm as application/wasm so browsers can stream-compile while downloading.

Download size matters on slow mobile data. A small Rust module of 40 KB loads instantly; a full C++ runtime of 4 MB does not.

The rest of this lesson

  • Where wasm pays off, and where it does notexplain
  • How many crossings?predict
  • Send a big array to wasmorder
  • Grow by whole pagesfill
  • Batch the byteschallenge
  • Badge quizquiz
  • WebAssembly, unit 3: complete!recap

Continue this lesson free — run real code in your browserright here

Continue with Google

See all 12 lessons of WebAssembly