Skip to content
rusthacks.dev
Web

Rust to WebAssembly and When It Is Worth the Effort

A guide to compiling Rust to WebAssembly: the targets, wasm-bindgen, calling between Rust and JavaScript, size, testing and when WebAssembly is worth it.

15 min read
Summarize in AI
Flat illustration for the post “Rust to WebAssembly and When It Is Worth the Effort”, composed around wasm.

WebAssembly is advertised with a number, "near native speed", and the number hides the real questions. Near native compared to what, doing which work, and at what cost in size, build complexity and the boundary between your Rust and the JavaScript around it? This guide answers them with a small module you can build yourself, a benchmark run in Node.js against an equivalent JavaScript function, and the one bug in the module that only appears when you compile for WebAssembly.

The module was built with Rust 1.99, edition 2024, for the wasm32-unknown-unknown target and run in Node.js 24.1. It uses no code generator and no extra crates, which keeps the mechanics visible. The later section on wasm-bindgen shows what the usual tooling adds, but you should see the raw ABI once, because everything the tools hide is happening underneath.

What WebAssembly is, in the terms that matter

A WebAssembly module is a compact binary of functions that run in a sandbox inside the host: a browser, Node.js, or a standalone runtime such as Wasmtime. The sandbox has three consequences that shape every design decision.

The module cannot touch the outside world on its own. No file system, no network, no DOM, no clock, unless the host passes functions in as imports. Whatever your Rust code needs from the world, it asks the host for.

The module has one block of memory, called linear memory, which is a resizable array of bytes that the module and the host can both read. WebAssembly has numeric types only: 32 and 64-bit integers and floats. A string, a struct or an array does not exist at the boundary. What crosses is a number, and for anything bigger, a pair of numbers: a pointer (an offset into linear memory) and a length.

And on the wasm32 target, pointers are 32 bits. That one fact, covered below, is the source of the module's bug.

When it is worth the effort

Before the code, the decision, because most projects that adopt WebAssembly should not.

SituationVerdict
CPU-heavy work on data already in memory: image filters, parsing, compression, simulationGood fit. The boundary is crossed rarely, the work is large
Reusing an existing Rust library in the browser or in a JavaScript plugin systemGood fit. Reuse is the main benefit, speed is secondary
Safe sandboxed plugins run by your own server (Wasmtime)Good fit. This is the strongest case outside the browser
UI logic, form validation, DOM manipulationPoor fit. The DOM is only reachable through JavaScript, and the boundary cost dominates
Many tiny calls between JS and RustPoor fit, as the measurement below shows
Anything JavaScript already does well enoughNot worth a second build pipeline

The test is simple: if you cannot name a chunk of work that takes tens of milliseconds and runs on data you can hand over in one call, WebAssembly will not pay for its complexity.

Build a module with a plain C interface

Set the crate type to cdylib and optimize for size, since download size is a cost you pay on every page view:

Cargo.tomlTOML
[package]
name = "wasmlab"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[profile.release]
opt-level = "s"
lto = true
codegen-units = 1
panic = "abort"
strip = true

Add the target once with rustup target add wasm32-unknown-unknown, then build with cargo build --release --target wasm32-unknown-unknown. The output is target/wasm32-unknown-unknown/release/wasmlab.wasm. Here is the whole library:

src/lib.rsrust
/// Count primes below `limit` with a sieve. Exported with a plain C ABI,
/// so any WebAssembly host can call it without generated glue.
#[unsafe(no_mangle)]
pub extern "C" fn count_primes(limit: u32) -> u32 {
    let limit = limit as usize;
    if limit < 3 {
        return 0;
    }
    let mut composite = vec![false; limit];
    let mut count = 0;
    for i in 2..limit {
        if !composite[i] {
            count += 1;
            // usize is 32 bits on wasm32: i * i wraps for i >= 65536, so check it.
            let Some(mut j) = i.checked_mul(i) else { continue };
            while j < limit {
                composite[j] = true;
                j += i;
            }
        }
    }
    count
}

/// Add two numbers. The cheapest possible call, to measure the boundary.
#[unsafe(no_mangle)]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a.wrapping_add(b)
}

/// Hand the host a block of linear memory it can write into.
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
    let mut buf = Vec::<u8>::with_capacity(len);
    let ptr = buf.as_mut_ptr();
    std::mem::forget(buf); // the host owns it until it calls `dealloc`
    ptr
}

/// # Safety
/// `ptr` and `len` must come from a matching earlier call to `alloc`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
    drop(unsafe { Vec::from_raw_parts(ptr, 0, len) });
}

/// Count the words in a UTF-8 buffer the host wrote into memory.
///
/// # Safety
/// `ptr..ptr + len` must be initialized bytes inside this module's memory.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn word_count(ptr: *const u8, len: usize) -> u32 {
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    match std::str::from_utf8(bytes) {
        Ok(text) => text.split_whitespace().count() as u32,
        Err(_) => u32::MAX, // signal "not UTF-8" to the caller
    }
}

#[unsafe(no_mangle)] is the edition 2024 spelling of #[no_mangle]: it keeps the symbol name count_primes so the host can find the export, and it is marked unsafe because exporting a symbol can collide with another one and Rust cannot check that. extern "C" gives the function a stable calling convention. The alloc, dealloc and word_count trio is how a string crosses the boundary, explained below.

The bug that only exists on wasm32

Look at the sieve's inner loop. The first version, which compiles without a warning and works natively, read let mut j = i * i;. Here is what each implementation returned for the primes below ten million, where the correct answer is 664,579:

Text
JS sieve, 10M       result=664579
Wasm sieve, 10M     result=664214

The Rust function returned 365 too few. Nothing crashed and nothing warned. The cause is that usize is 32 bits on wasm32, so for any i of 65,536 or more, i * i is at least 2^32 and wraps around in a release build (overflow checks are off by default in release). The wrapped value is a small number, the loop marks the wrong cells as composite, and some primes are erased. Natively, usize is 64 bits and the same expression is fine, so the unit tests you ran on your laptop all passed.

The fix, in the listing above, is i.checked_mul(i): when the multiplication overflows, the square is certainly greater than limit, so there is nothing to mark and the loop moves on. The general lesson is to test WebAssembly builds on the WebAssembly target. cargo test runs natively and cannot see this class of bug. Run the same checks against the compiled .wasm, as the benchmark below does, or run your tests under a WebAssembly runtime with wasmtime as the Cargo runner. And be suspicious of usize arithmetic that was sized for 64-bit: index math, byte counts and hash mixing all deserve a second look.

Call it from JavaScript

A .wasm file can be loaded with no tooling at all. This is the entire host program for Node.js, with a JavaScript implementation of the same sieve alongside:

bench.mjsJavaScript
import { readFileSync } from 'node:fs';

const bytes = readFileSync(new URL('./target/wasm32-unknown-unknown/release/wasmlab.wasm', import.meta.url));
const { instance } = await WebAssembly.instantiate(bytes, {});
const { count_primes, add } = instance.exports;

function countPrimesJs(limit) {
  const composite = new Uint8Array(limit);
  let count = 0;
  for (let i = 2; i < limit; i++) {
    if (!composite[i]) {
      count++;
      for (let j = i * i; j < limit; j += i) composite[j] = 1;
    }
  }
  return count;
}

function time(label, fn, runs = 20) {
  fn(); // warm up the JIT
  const start = performance.now();
  let result;
  for (let i = 0; i < runs; i++) result = fn();
  const ms = (performance.now() - start) / runs;
  console.log(`${label.padEnd(26)} ${ms.toFixed(2).padStart(8)} ms/run  result=${result}`);
}

time('JS sieve, 10M', () => countPrimesJs(10_000_000));
time('Wasm sieve, 10M', () => count_primes(10_000_000));

In a browser the only difference is how you get the bytes: WebAssembly.instantiateStreaming(fetch('wasmlab.wasm')). The {} second argument is the import object, where you would pass host functions the module calls, such as a logger. This module imports nothing.

What the numbers say

Five consecutive runs of the benchmark on an Apple silicon laptop, sieve of 10 million, milliseconds per run:

RunJavaScriptWebAssembly
170.439.1
266.349.6
347.342.9
462.636.4
541.528.0

Compiled natively with the same code, the sieve took 23 ms per run. Read this table without enthusiasm or disappointment. WebAssembly was faster in every run, by a factor between 1.1 and 1.7, and slower than native by about the same margin. The spread between runs is as large as the difference, so any claim more precise than "somewhat faster" would be invented. The reason the gap is modest is that V8 compiles hot JavaScript with an excellent optimizing JIT, and a sieve over a typed array is exactly the code it handles best. WebAssembly's advantages show up more strongly on code that JavaScript handles worse: 64-bit integer math, tight numeric kernels using SIMD, large data structures that fight the garbage collector, and anything where predictable performance matters more than peak performance, since a module has no JIT warm-up and no deoptimization.

The boundary has a price

The other half of the benchmark counts five million calls of a trivial function, add, from JavaScript into WebAssembly and the same calls into a JavaScript function:

Text
5000000 tiny wasm calls: 49.9 ms
5000000 tiny JS calls:   6.5 ms

Each crossing costs roughly ten nanoseconds, against well under two for a call the JIT can inline. That is invisible when a call does ten milliseconds of work and ruinous when a loop crosses the boundary a million times. This is the practical rule for designing the interface: make few calls and give each a lot to do. Process a whole image, not a pixel; parse a whole document, not a token. If the natural API is "call Rust per item", batch the items into one buffer and make one call.

Passing data: pointers and lengths

A number is easy to pass. A string is not, because the module's memory is separate from the host's. The pattern is: the module exports an allocator, the host asks it for a block, writes the bytes into linear memory at that address, and then calls the function with the address and length. alloc, dealloc and word_count in the library implement it, and the host side is:

words.mjsJavaScript
import { readFileSync } from 'node:fs';

const bytes = readFileSync(new URL('./target/wasm32-unknown-unknown/release/wasmlab.wasm', import.meta.url));
const { instance } = await WebAssembly.instantiate(bytes, {});
const { memory, alloc, dealloc, word_count } = instance.exports;

function wordCount(text) {
  const data = new TextEncoder().encode(text);
  const ptr = alloc(data.length);
  new Uint8Array(memory.buffer, ptr, data.length).set(data); // fetch memory.buffer AFTER alloc
  const n = word_count(ptr, data.length);
  dealloc(ptr, data.length);
  return n;
}

console.log(wordCount('the quick brown fox'));
console.log(wordCount('  spaced   out  '));
console.log(wordCount('naïve café 東京'));
console.log('memory pages:', memory.buffer.byteLength / 65536);
Text
4
2
3
memory pages: 18

The three counts are right, including for non-ASCII text (naïve café 東京 is three words in 22 bytes). One line carries a hazard worth memorizing: memory.buffer is fetched after alloc, not before. Allocating can grow linear memory, and growth replaces the underlying ArrayBuffer, which detaches every view you held earlier. Code that caches new Uint8Array(memory.buffer) at startup works in testing and then throws a "detached ArrayBuffer" error, or silently writes to nothing, the first time a large allocation grows memory.

On the Rust side, word_count is unsafe because it trusts the host's pointer and length: it builds a slice from raw parts, and a host that lies could make it read outside its memory. The sandbox contains the damage, since a bad access traps the module and cannot escape it, but your module should still validate what it can. Notice also the return convention: invalid UTF-8 returns u32::MAX, a sentinel, because the boundary has no Result. Richer errors need either an out-parameter in memory or a second export that fetches the last error.

The module's memory started at 18 pages of 64 KiB, about 1.1 MiB, before any large work. Linear memory only grows and never shrinks, so a module that once allocated 500 MB holds it until the instance is dropped. Design long-running modules so peak use is bounded.

Size: how big is the download

The module above is 15,571 bytes. Before std::str::from_utf8 and the allocation functions it was 13,911, and a module built without size optimization or with formatting machinery pulled in is many times larger. Size grows quickly when code pulls in formatting (format!, println! and {:?} bring in a large chunk of core::fmt), panics with messages, and big dependencies. Four habits keep modules small:

  1. Set opt-level = "s" or "z", lto = true, codegen-units = 1, panic = "abort" and strip = true, as in the manifest above.
  2. Avoid formatting and unwrap with messages in code paths you ship. Return error codes.
  3. Run wasm-opt -Oz from the Binaryen project on the output. It routinely removes another 10 to 20 percent.
  4. Check what is big with twiggy top before guessing, and serve the file compressed: a .wasm file gzips or Brotli-compresses to roughly a third.

What wasm-bindgen adds

Hand-written extern "C" works for numbers and buffers. For strings, structs, closures, promises and DOM access, wasm-bindgen generates both sides of the glue: Rust attributes on one side, and a JavaScript wrapper that marshals values through linear memory on the other.

src/lib.rsrust
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn word_count(text: &str) -> u32 {
    text.split_whitespace().count() as u32
}

#[wasm_bindgen]
pub struct Counter {
    total: u32,
}

#[wasm_bindgen]
impl Counter {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Counter {
        Counter { total: 0 }
    }

    pub fn add(&mut self, text: &str) -> u32 {
        self.total += word_count(text);
        self.total
    }
}

Build it with wasm-pack build --target web and import the generated package from JavaScript as an ordinary ES module: new Counter().add("hello world"). The convenience has a cost the raw version made visible: every &str argument is encoded to UTF-8 and copied into linear memory on each call, and every String returned is copied out. For large data, pass &[u8] or typed arrays and keep results in memory the host reads as a view. The lab behind this guide did not run the wasm-bindgen example, so treat it as the documented usage and build it before copying it into a project.

Outside the browser

The same .wasm runs server-side in Wasmtime or Wasmer, which is where WebAssembly's sandbox becomes a feature rather than a constraint. A host application loads a user-supplied module, gives it exactly the functions it may call, caps its memory and its fuel (a count of instructions), and runs untrusted code safely. Targets matter here: wasm32-wasip1 gives the module a system interface for files and clocks that the host grants selectively. That is covered in sandboxing untrusted code from Rust with WebAssembly.

A real program in the sandbox: the WASI target

wasm32-unknown-unknown has no system interface at all. The wasm32-wasip1 target compiles ordinary Rust, with std::fs, std::env, standard input and output, against the WebAssembly System Interface, where the host decides what each of those can reach. This is how the capability model becomes visible. The program below reads standard input, prints its arguments, and tries to read a file from /data:

src/main.rsrust
use std::io::Read;

fn main() {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).unwrap();
    let args: Vec<String> = std::env::args().skip(1).collect();
    println!("args: {args:?}");
    println!("{}", input.trim().to_uppercase());
    match std::fs::read_to_string("/data/note.txt") {
        Ok(text) => println!("read from preopened dir: {}", text.trim()),
        Err(e) => println!("no access to /data: {e}"),
    }
}

Build it with cargo build --release --target wasm32-wasip1 and run it from a small Node.js host, once with no directories granted and once with a single directory mapped to /data:

run.mjsJavaScript
import { readFileSync } from 'node:fs';
import { WASI } from 'node:wasi';

const grant = process.argv[2] === 'grant';
const wasi = new WASI({
  version: 'preview1',
  args: ['shout', 'one', 'two'],
  preopens: grant ? { '/data': new URL('./allowed', import.meta.url).pathname } : {},
});
const module = await WebAssembly.compile(readFileSync(new URL('./target/wasm32-wasip1/release/shout.wasm', import.meta.url)));
const instance = await WebAssembly.instantiate(module, wasi.getImportObject());
wasi.start(instance);
Text
$ echo "quiet words" | node run.mjs
args: ["one", "two"]
QUIET WORDS
no access to /data: No such file or directory (os error 44)

$ echo "quiet words" | node run.mjs grant
args: ["one", "two"]
QUIET WORDS
read from preopened dir: hello from the host

The same binary produced two different behaviors, and the difference is a line in the host: preopens maps a host directory to a path the module sees. Without it, /data does not exist for the module, whatever the Rust code asks for. With it, the module can read that one directory and nothing above it. That is the property that makes WebAssembly attractive for running code you do not fully trust: the permission list is explicit, deny-by-default, and enforced outside the module. The unoptimized release binary here is 106,293 bytes, mostly std's formatting and I/O; the size settings from earlier would shrink it substantially.

The WASI line in the sand deserves one caution. The interface has been evolving (the preview1 generation used here, then component-model based preview2 in Wasmtime), and a host and a module must agree on the version. If a module fails to instantiate with an unknown import named wasi_snapshot_preview1 or wasi:cli, the host and the target are on different generations, and the fix is to match them, not to debug your code.

Debugging a module

Debugging is the weak point, so plan for it. A panic with panic = "abort" becomes an unreachable trap with a stack of numeric function indexes, which tells you nothing. Three things help. In development, build with debug = true and strip = false, so browsers' developer tools can show Rust function names in the stack; Chrome can even step through source with DWARF support enabled. Set a panic hook that forwards the message to the host (console_error_panic_hook in the wasm-bindgen world, or an imported log function in the raw one), so a panic prints its text rather than trapping silently. And test the logic natively first. Keep the algorithmic core in a plain Rust library with ordinary unit tests, and make the wasm crate a thin shell of exports around it, so only the boundary code needs the WebAssembly toolchain to debug.

Checklist before you ship a module

  • A benchmark on your real workload, in your real host, repeated enough to see the spread. Do not ship on a single run.
  • A test that runs against the compiled .wasm, not only natively, to catch the usize class of bug.
  • A size budget enforced in CI: fail the build if the compressed module grows past a limit.
  • Few boundary calls, each carrying a batch of work.
  • A plan for memory: bounded peak use, and views fetched after any call that can allocate.

When not to bother

If the work finishes in a few milliseconds in JavaScript, the build pipeline, the glue and the debugging story (stack traces in a .wasm are far harder to read than in JavaScript) cost more than they return. If your logic lives next to the DOM, keep it in JavaScript or TypeScript. If a Web Worker running optimized JavaScript meets your performance target, use it. Choose WebAssembly when you have a real compute kernel or a Rust library worth reusing, when you measured the benefit on the host that matters, and when you accept maintaining two build outputs. For an adjacent way to call Rust from another language runtime, see Node addons in Rust with napi-rs.

Also inRust
Taggedwasm
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.