🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly: When to Use It

WebAssembly fits work that taxes the processor. It earns its place when plain JavaScript feels slow.

A spreadsheet recalculates many cells

A sheet adds up a whole column at once.

const cells = [2, 4, 6, 8];
const total = cells.reduce((sum, n) => sum + n, 0);
console.log(total);

A filter touches every pixel

A filter changes each pixel value by the same amount.

const pixels = [10, 20, 30];
const bright = pixels.map((p) => p + 5);
console.log(bright.join(", "));

Example

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

Key points

  • Use WebAssembly to edit photos and filter pixels fast.
  • Use WebAssembly to encode video and decode audio streams.
  • Use WebAssembly to run game physics and 3D scenes smoothly.
  • Use WebAssembly to check passwords and encrypt files safely.
  • Use WebAssembly to recalculate large spreadsheets without delay.

In this example, a WebAssembly module adds the numbers 0 to 4 one by one. The loop is the kind of repeated number work that taxes a processor. WebAssembly earns its place on heavy repeated work like this.

Note

The job must be big enough to repay the cost of loading the file.

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

Which job fits WebAssembly best?