WebAssembly Introduction
Learn the basics of WebAssembly and its applications.
By EMEPublished: February 20, 2025
webassemblywasmperformancecompiled code
A Simple Analogy
WebAssembly is like compiling code to run natively in browsers. Same language, massive performance boost.
Why WebAssembly?
- Performance: 10-100x faster than JavaScript
- Languages: C++, Rust, Go compile to WASM
- Interop: Works alongside JavaScript
- Portability: Runs everywhere
- Security: Sandboxed execution
.wasm Module
// C# to WASM using Blazor
@page "/calculator"
<h3>Calculator</h3>
<input @bind="input" />
<button @onclick="Calculate">Calculate</button>
<p>Result: @result</p>
@code {
private string input;
private int result;
private void Calculate()
{
result = int.Parse(input) * 2;
}
}
Rust to WASM
# Setup
cargo install wasm-pack
cargo new --lib my_wasm
cd my_wasm
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u32 {
if n <= 1 {
return n;
}
fibonacci(n - 1) + fibonacci(n - 2)
}
wasm-pack build --target web
JavaScript Integration
// Load WASM module
import init, { add, fibonacci } from './my_wasm.js';
async function main() {
await init();
console.log(add(3, 4)); // 7
console.log(fibonacci(10)); // 55
}
main();
Calling from JavaScript
<button onclick="runWasm()">Run Heavy Computation</button>
<script type="module">
import init, { process_data } from './wasm_module.js';
async function runWasm() {
await init();
const result = process_data(largeArray);
console.log(result);
}
</script>
Best Practices
- Heavy lifting: Use for CPU-intensive work
- Small modules: Keep WASM size small
- Incremental: Migrate pieces gradually
- Profile: Measure before/after
- Async: Load modules asynchronously
Related Concepts
- JavaScript modules
- Performance optimization
- Compiled languages
- Sandboxing
Summary
WebAssembly enables high-performance compiled code in browsers. Ideal for heavy computation, image processing, and game engines.