🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Performance

WebAssembly runs at near-native speed for heavy work. Speed claims still need a measurement.

Shrink a module with wasm-opt

One pass trims size and speeds the code.

wasm-opt -O3 input.wasm -o output.wasm

Count the calls first

Add 1 and 1 one hundred times. The total is exact.

let total = 0;
for (let i = 0; i < 100; i++) {
  total += instance.exports.add(1, 1);
}
console.log(total);

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  let total = 0;
  for (let i = 0; i < 1000; i++) {
    total += instance.exports.add(1, 1);
  }
  console.log("1000 calls:", total);
  total = 0;
  for (let i = 0; i < 10000; i++) {
    total += instance.exports.add(1, 1);
  }
  console.log("10000 calls:", total);
})();

Key points

  • WebAssembly is a binary format that runs close to native speed.
  • Use wasm-opt to shrink a module and speed it up.
  • Browsers cache compiled modules for later visits.
  • Measure before claiming a speedup.
  • Count calls first, then time them.
  • The demo below compares two call counts, not fake timings.
  • Fast code is proven by measurement, not by a claim.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add one thousand times and logs the total, then calls add ten thousand times and logs that total. The totals are exact sums, not timings.

Note

this lesson gives no benchmark numbers.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What should you do before claiming a speedup?