Introduction
WebAssembly (WASM) brings near-native performance to web applications, enabling compute-intensive tasks like image processing, cryptography, and scientific computing to run efficiently in the browser.
Compiling Rust to WebAssembly
// lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
#[wasm_bindgen]
pub fn process_image(data: &[u8]) -> Vec<u8> {
// Image processing logic
data.iter().map(|&x| x.saturating_add(50)).collect()
}
Building and Loading WASM
# Install wasm-pack
cargo install wasm-pack
# Build for web
wasm-pack build --target web
// JavaScript integration
import init, { fibonacci, process_image } from './pkg/my_wasm.js';
async function runWasm() {
await init();
console.log(fibonacci(10)); // 55
const imageData = new Uint8Array([100, 150, 200]);
const processed = process_image(imageData);
console.log(processed); // [150, 200, 250]
}
Performance Comparison
// JavaScript implementation
function fibJS(n: number): number {
if (n <= 1) return n;
return fibJS(n - 1) + fibJS(n - 2);
}
// Benchmark
console.time('JS');
fibJS(40);
console.timeEnd('JS'); // ~1000ms
console.time('WASM');
fibonacci(40);
console.timeEnd('WASM'); // ~50ms (20x faster!)