Skip to content
WebAssembly

Performance

Benchmark and parallelize WASM workloads.

By EZ4Code Team
performancebenchmarkthreads

Code

// Bench: WASM vs JS for a tight numeric loop
function jsSum(n) {
  let total = 0;
  for (let i = 0; i < n; i++) total += i;
  return total;
}

const { sum: wasmSum } = instance.exports;
const N = 100_000_000;

console.time("js");
jsSum(N);
console.timeEnd("js");

console.time("wasm");
wasmSum(N);
console.timeEnd("wasm");

// Threads via SharedArrayBuffer (requires COOP/COEP headers)
// const shared = new WebAssembly.Memory({
//   initial: 1, maximum: 10, shared: true,
// });

Explanation

WebAssembly shines on tight numeric loops where predictable types and near-native code beat JIT warmup. Measure with console.time or performance.now, and reuse the same instance to avoid recompilation. For CPU-heavy parallelism, combine SharedArrayBuffer-backed memory with Web Workers, which requires cross-origin isolation headers.

More WebAssembly Snippets