Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Performance and Debugging

WebAssembly Performance

Learn when WebAssembly is faster than JavaScript, how to benchmark fairly, why boundary crossings and copies cost time, and how startup, streaming and tiering affect real pages.

"WebAssembly is faster than JavaScript" is the most repeated claim about the technology, and also the most misleading in its short form. Wasm can be much faster for some jobs, about the same for others, and slower when used badly. Modern JavaScript engines compile hot code to machine code and are very good at it. What WebAssembly offers is not a magic speed boost but predictability: a compact binary that decodes quickly, has static types, needs no warm-up guesses, and behaves the same from run to run.

This lesson gives you a mental model for where time goes, a fair way to measure it, and a checklist for deciding whether a task belongs in Wasm at all.

Where the speed comes from

JavaScript engines start by running code in an interpreter and observe it. After a function is hot they compile an optimized version that assumes the types they saw (for example "this variable is always a small integer"). If the assumption breaks, they throw the optimized code away (deoptimization) and fall back. This is fast on average but can have surprising pauses.

WebAssembly arrives with types already fixed. The engine can compile it directly, and most engines use two tiers: a very fast baseline compiler that produces running code almost immediately, and an optimizing compiler that replaces it for hot functions. Nothing needs to be guessed, so there is no deoptimization.

Why Wasm can be fast

Static types No guessing, no deopts.
Compact binary Decodes faster than parsing JS.
Two tiers Baseline now, optimized later.
Low-level ops Integers, SIMD, no GC pauses.

Predictable speed is the real win.

1 / 2

Benchmark 1: tight numeric code

The best case for WebAssembly is a hot loop over numbers. The recursive Fibonacci function below is a classic stress test because it is almost all function calls and integer additions. We run the same algorithm in JavaScript and in a hand-assembled module, check that the answers agree, and time both. Run it a few times: the numbers vary from machine to machine, and on many engines JavaScript is surprisingly close.

Node.js Fibonacci: JavaScript versus WebAssembly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the habits that make this a fair benchmark: the same algorithm, a warm-up run, several samples and the median (not the single best or worst run). Never trust a benchmark that runs once, compares different algorithms, or measures inside a throttled background tab.

Benchmark 2: the cost of crossing the boundary

Every call from JavaScript into Wasm and back has overhead, and arguments and results must be converted. Engines have made this cheap, but "cheap" times a million is not free. Compare doing the work in one call against doing it in a million calls:

Node.js One big call versus a million small calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare the two "per addition" lines. Engines make plain numeric calls quite cheap, so the gap here is modest, and the loop inside the module is not at its fastest while the engine is still compiling it. The gap becomes large as soon as each call also has to copy a string or an array. If your design makes the host call a tiny function per element, you pay that overhead per element. Batch the work: pass a pointer to a whole array and let the module loop.

The copying problem

Strings and arrays do not cross the boundary as objects; they are copied into linear memory (see Passing Strings and Structs). Copying a megabyte is quick, but doing it for every frame of an animation, or twice per call, adds up. Techniques that help:

  • Keep data resident. Allocate a buffer once and reuse it; write input into it, run the module, read results from the same view.
  • Use views, not copies. new Uint8Array(memory.buffer, ptr, len) shares the bytes; slice copies them.
  • Process in place. Mutate the buffer inside Wasm instead of returning a new one.
  • Transfer, do not clone, when sending buffers to workers (postMessage(buf, [buf])).

Startup cost

A Wasm file has to be downloaded, compiled and instantiated before it runs. For a large module that can dominate the whole run time, so how you load matters as much as how fast the code is.

Technique Effect
WebAssembly.instantiateStreaming(fetch(url)) Compiles while the bytes download, so it is ready right after the last byte
Serve with Content-Type: application/wasm Required for streaming to work
HTTP compression (gzip, Brotli) Wasm compresses well, often to a third of its size
Compile once, instantiate many times WebAssembly.Module can be reused, even sent to a worker
Lazy loading Load heavy modules when the feature is first used
Browser code cache Engines cache compiled code for repeat visits

See Bundlers and Loading Strategies for loader code.

Memory and garbage collection

A module with linear memory manages its own memory, so there are no garbage-collection pauses in the code you compiled from C, C++ or Rust. That is attractive for games and audio, where a long pause means a glitch. Memory can only grow, never shrink: if a program briefly needs 500 MB, the tab holds 500 MB until the instance is discarded. Plan for peak usage and release the whole instance when finished.

When should you use WebAssembly?

flowchart TD
  A["Slow task in the page"] --> B{"Mostly number crunching on large data?"}
  B -- "No (DOM, network, small data)" --> C["Optimize the JavaScript first"]
  B -- "Yes" --> D{"Existing C, C++ or Rust library?"}
  D -- "Yes" --> E["Compile it: big win in effort"]
  D -- "No" --> F{"Can you batch calls and reuse buffers?"}
  F -- "No" --> C
  F -- "Yes" --> G["Wasm is a good candidate: measure it"]

Decision flow: Wasm pays off for batched numeric work and for reusing existing native code.

Good candidates include image and video processing, audio synthesis, compression, cryptography, physics, parsers, games and scientific code. Poor candidates include form handling, DOM updates and anything dominated by network latency.

A measuring checklist

  1. Measure the whole user-visible task, including download, compile and copying, not just the inner loop.
  2. Use performance.now() or the browser's Performance panel, with warm-up and several runs.
  3. Compare against optimized JavaScript (typed arrays, no allocation in the loop), not a naive version.
  4. Test on a mid-range phone, not only your fast laptop.
  5. Re-measure after each engine update; both sides keep improving.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main performance advantage of WebAssembly over JavaScript?

    Wasm is not universally faster, but its fixed types remove the guessing and deoptimization that make JavaScript timing less predictable.
  2. 2. A page calls a tiny wasm function once for every pixel. What is the best fix?

    Each crossing has overhead. Batching the work into one call removes that overhead per pixel.
  3. 3. Which API compiles a module while it is still downloading?

    Streaming instantiation overlaps download and compilation. The server must send Content-Type application/wasm.
  4. 4. Which benchmark habit gives the most trustworthy numbers?

    Warm-up avoids measuring compilation, and the median ignores outliers caused by other processes.

Summary

  • WebAssembly gives predictable, near-native speed for numeric work, but modern JavaScript is fast too, so measure.
  • Boundary crossings and data copies cost time; batch work, reuse buffers and use memory views.
  • Startup matters: use streaming instantiation, correct MIME type, compression, caching and lazy loading.
  • Linear memory has no GC pauses but only grows.
  • Benchmark fairly with warm-ups, the same algorithm, the median and real devices.

Next: Debugging WebAssembly