Performance Optimization

40.1 Understand the Costs

Compression (Brotli), code size optimization (Module 41), caching, CDN

instantiateStreaming (compile while downloading), tiered compilation, cache WebAssembly.Module (IndexedDB where supported), lazy-load modules, AOT in runtimes JS↔Wasm boundary

Batch calls, avoid frequent string conversions, keep data in Wasm memory, use views instead of copies

Pre-size INITIAL_MEMORY. Growth may copy/remap. Recreate views.

Engines use guard pages (virtual memory) for wasm32. Memory64 may need explicit checks.

GC (WasmGC/glue) Avoid excessive allocations. Reuse objects.

40.2 Compiler-Level Optimizations

Enable LTO, codegen-units = 1, and opt-level = 3 (speed) or "s"/"z" (size). Use PGO where supported (Binaryen and LLVM have profile-guided options).

Use SIMD (Module 22), threads (Module 23), trunc_sat (no trap checks), bulk memory, and multi-value.

emcc -O3 -flto -msimd128 ...                                   # Emscripten
RUSTFLAGS="-C target-feature=+simd128,+bulk-memory" cargo build --release
wasm-opt -O3 --enable-simd in.wasm -o out.wasm                 # Binaryen post-optimization
wasm-opt -O4 --converge in.wasm -o out.wasm                    # aggressive

40.3 Algorithmic and Data-Layout Tips

Choose cache-friendly data layouts (struct of arrays), avoid unnecessary allocation in hot loops, use integer math where possible, and prefer f32 when precision allows (SIMD packs 4 lanes).

Minimize call_indirect/dynamic dispatch in hot paths (or use typed function refs).

For the web: offload heavy Wasm work to Web Workers to keep the main thread responsive. Use OffscreenCanvas for rendering in workers.

40.4 Measuring

Browser DevTools Performance panel (Wasm frames shown with names if the name section exists), performance.now(), perf with Wasmtime (--profile=perfmap / jitdump), Wasmtime's guest profiler, criterion benchmarks for Rust (compare native vs Wasm), and benchmarks under realistic loads.