Performance Tips
WebAssembly is typically within a small factor of native speed and much more predictable than JavaScript. But "rewrite it in Wasm" doesn't automatically make things faster. Where the time goes matters more than the language. This lesson collects the practical rules. (The examples count work rather than measure time, since timings vary between machines.)
1. Cross the boundary rarely
A call between JavaScript and Wasm is cheap, but not free, and every string or array you pass must be copied. The winning pattern is batching: one call that processes a whole array beats a thousand calls that each process one element.
// Count how often each approach crosses the JS <-> Wasm boundary and how many bytes it copies.
let crossings = 0, copied = 0;
const wasm = { // stand-in for exported functions
brightenOne: (v) => { crossings++; return Math.min(v + 40, 255); },
brightenAll: (ptr, len) => { crossings++; return len; },
};
const pixels = new Uint8Array(640 * 480);
// chatty: one call per pixel
for (let i = 0; i < pixels.length; i++) pixels[i] = wasm.brightenOne(pixels[i]);
console.log('per-pixel calls:', crossings.toLocaleString('en-US'));
// batched: copy once, call once (or better: keep the pixels in Wasm memory all along)
crossings = 0;
copied += pixels.length;
wasm.brightenAll(1024, pixels.length);
console.log('batched calls:', crossings, 'bytes copied:', copied.toLocaleString('en-US'));per-pixel calls: 307,200
batched calls: 1 bytes copied: 307,200
Better still: keep data in Wasm memory and let JavaScript read it through a typed array view only when needed
(e.g. hand the pixel buffer straight to ImageData).
2. Keep hot values in locals
Locals compile to CPU registers; memory accesses are loads and stores with bounds checks. Engines are good at optimising, but accumulating in memory inside a loop still costs more than accumulating in a local:
(module
(import "console" "log" (func $log2 (param i32 i32)))
(memory 1)
(global $loads (mut i32) (i32.const 0))
(global $stores (mut i32) (i32.const 0))
;; sum 1..n keeping the running total in memory at address 0
(func $sum_in_memory (param $n i32) (result i32)
(i32.store (i32.const 0) (i32.const 0))
(block $done (loop $next
(br_if $done (i32.eqz (local.get $n)))
(i32.store (i32.const 0) (i32.add (i32.load (i32.const 0)) (local.get $n)))
(global.set $loads (i32.add (global.get $loads) (i32.const 1)))
(global.set $stores (i32.add (global.get $stores) (i32.const 1)))
(local.set $n (i32.sub (local.get $n) (i32.const 1)))
(br $next)))
(i32.load (i32.const 0)))
;; the same with a local accumulator: zero memory traffic
(func $sum_in_local (param $n i32) (result i32)
(local $acc i32)
(block $done (loop $next
(br_if $done (i32.eqz (local.get $n)))
(local.set $acc (i32.add (local.get $acc) (local.get $n)))
(local.set $n (i32.sub (local.get $n) (i32.const 1)))
(br $next)))
(local.get $acc))
(func (export "main")
(call $log2 (call $sum_in_memory (i32.const 1000)) (call $sum_in_local (i32.const 1000)))
(call $log2 (global.get $loads) (global.get $stores))))500500 500500
1000 1000
Same answer, but the first version performs 1000 loads and 1000 stores the second doesn't need.
3. Use SIMD for data-parallel loops
Processing 4 floats or 16 bytes per instruction can give a big speedup for image, audio and math kernels. Compile
with -msimd128 (C/C++) or +simd128 (Rust), or write v128 code directly:
(module
(import "console" "log" (func $log2 (param i32 i32)))
(memory 1)
(global $ops (mut i32) (i32.const 0))
;; add 10 to 64 bytes, scalar: one byte per iteration
(func $scalar (param $p i32) (param $n i32)
(block $done (loop $next
(br_if $done (i32.eqz (local.get $n)))
(i32.store8 (local.get $p) (i32.add (i32.load8_u (local.get $p)) (i32.const 10)))
(global.set $ops (i32.add (global.get $ops) (i32.const 1)))
(local.set $p (i32.add (local.get $p) (i32.const 1)))
(local.set $n (i32.sub (local.get $n) (i32.const 1)))
(br $next))))
;; the same with SIMD: 16 bytes per iteration
(func $simd (param $p i32) (param $n i32)
(block $done (loop $next
(br_if $done (i32.eqz (local.get $n)))
(v128.store (local.get $p) (i8x16.add (v128.load (local.get $p)) (i8x16.splat (i32.const 10))))
(global.set $ops (i32.add (global.get $ops) (i32.const 1)))
(local.set $p (i32.add (local.get $p) (i32.const 16)))
(local.set $n (i32.sub (local.get $n) (i32.const 16)))
(br $next))))
(func (export "main")
(local $before i32)
(call $scalar (i32.const 0) (i32.const 64))
(local.set $before (global.get $ops))
(global.set $ops (i32.const 0))
(call $simd (i32.const 64) (i32.const 64))
(call $log2 (local.get $before) (global.get $ops))
(call $log2 (i32.load8_u (i32.const 5)) (i32.load8_u (i32.const 69))))) ;; both became 1064 4
10 10
4. Ship less code
Download and compile time often dominate. Shrink the binary:
| Technique | How |
|---|---|
| Optimise for size | -Oz / opt-level = "z", then wasm-opt -Oz |
| Strip debug info and names | wasm-strip, strip = true in Cargo |
| Avoid heavy formatting | printf/format! pull in large code; prefer simple number output |
| Compress | serve with Brotli or gzip: Wasm compresses well |
| Stream | instantiateStreaming overlaps download and compilation |
| Cache | compiled code is cached by the browser for the same URL and headers |
5. Avoid memory-growth surprises
- Reserve a sensible initial memory so the app doesn't grow it in small steps (each growth may copy the whole buffer).
- Re-create JS views after anything that might grow memory, but don't re-create them on every call either.
6. Measure, don't guess
- Profile with the browser's Performance panel; Wasm functions show up by name if you keep the name section in development builds.
- Compare against well-written JavaScript: modern JITs are excellent at simple numeric loops, so the gain may be small. Wasm shines for predictable performance, existing native libraries, and SIMD/threads.
- Benchmark after warm-up: the first calls may run baseline-compiled code before the optimising tier finishes.
Test yourself
Which pattern is fastest for processing a large array with Wasm?
- Call an export once per element
- Copy the array into Wasm memory once (or keep it there) and process it in one call
- Convert it to JSON first
- Use externref for each element
Why can a running sum in a local be faster than one in memory?
- Locals are larger
- Locals map to registers, while memory accesses are loads/stores with bounds checks
- Memory is read-only
- Locals are shared between threads
Which tool shrinks and optimises an existing .wasm file?
wasm-opt(Binaryen)wat2wasmnode --inspectnpm audit