DEV Community

Atlas Whoff
Atlas Whoff

Posted on

WebAssembly in JavaScript: When and How to Use WASM

WebAssembly in JavaScript: When and How to Use WASM

WebAssembly runs near-native performance code in the browser. Here's when it actually makes sense to use it.

What WASM Is Good For

WASM excels at:

  • CPU-intensive computation (video encoding, image processing, physics)
  • Porting existing C/C++/Rust code to the browser
  • Consistent performance across browsers

WASM is NOT needed for:

  • DOM manipulation (JS is faster for this)
  • Network requests
  • Most business logic
  • Anything that runs in <10ms anyway

Calling WASM From JavaScript

// Load and instantiate a WASM module
const response = await fetch('module.wasm');
const buffer = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(buffer);

// Call WASM functions directly
const result = instance.exports.fibonacci(40);
console.log(result); // Returns in ~1ms vs ~2000ms in pure JS
Enter fullscreen mode Exit fullscreen mode

Rust to WASM With wasm-pack

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

#[wasm_bindgen]
pub fn process_image(data: &[u8], width: u32, height: u32) -> Vec<u8> {
    // CPU-intensive image processing
    data.chunks(4)
        .flat_map(|pixel| {
            let r = pixel[0];
            let g = pixel[1];
            let b = pixel[2];
            let gray = (0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32) as u8;
            vec![gray, gray, gray, pixel[3]]
        })
        .collect()
}
Enter fullscreen mode Exit fullscreen mode
wasm-pack build --target web
Enter fullscreen mode Exit fullscreen mode
import init, { process_image } from './pkg/my_module.js';

await init();

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const processed = process_image(imageData.data, canvas.width, canvas.height);
Enter fullscreen mode Exit fullscreen mode

Real-World WASM Use Cases

  • Figma: complex vector rendering engine in WASM
  • Photoshop for Web: entire image processing pipeline
  • SQLite in the browser: @sqlite.org/sqlite-wasm
  • ffmpeg.wasm: client-side video transcoding

Performance Comparison

// Benchmark: fibonacci(40)
console.time('js');
fibJS(40); // ~2000ms
console.timeEnd('js');

console.time('wasm');
fibWasm(40); // ~1ms
console.timeEnd('wasm');
// 2000x speedup for this specific workload
Enter fullscreen mode Exit fullscreen mode

For most SaaS applications, Web Workers (pure JS, multithreaded) are sufficient before reaching for WASM. The Ship Fast Skill Pack includes patterns for both Web Workers and WASM integration.

Top comments (0)