WebAssembly (WASM): High-Performance Web Applications
Table of Contents
Background
WebAssembly (WASM) is a binary instruction format designed as a portable compilation target for high-level languages. It enables deployment on the web for client and server applications with near-native performance.
Key Features
| Feature | Description |
|---|---|
| Fast | Near-native execution speed |
| Safe | Memory-safe sandboxed execution |
| Portable | Hardware and platform independent |
| Language-agnostic | Compile from C/C++, Rust, Go, AssemblyScript |
AssemblyScript
AssemblyScript compiles a strict subset of TypeScript to WebAssembly:
// assembly/index.ts
export function fibonacci(n: i32): i32 {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
export function factorial(n: i32): i32 {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Build and use:
# Install npm install --save-dev assemblyscript # Compile npx asc assembly/index.ts -o build/module.wasm # Use in JavaScript const { fibonacci } = await WebAssembly.instantiate(wasmBuffer); console.log(fibonacci(10)); // 55
Rust to WebAssembly
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
#[wasm_bindgen]
pub fn sum(a: i32, b: i32) -> i32 {
a + b
}
# Build with wasm-pack wasm-pack build --target web
Browser Integration
// Load and instantiate WASM module async function loadWasm() { const response = await fetch('module.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes); // Call exported functions const result = instance.exports.fibonacci(10); console.log(result); // 55 }
Use Cases
- Image/video processing in browser
- Games and physics engines
- Cryptography and compression
- CAD and 3D rendering
- Running existing C/C++ code in browser