WebAssembly (Wasm)
WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.
1. The Core Concept
WebAssembly allows code written in languages like C, C++, Rust, and Go to run on the web at near-native speed.
- Binary Format: It is delivered as a compact binary file (
.wasm), which is faster to download and parse than text-based JavaScript. - Performance: It executes at speeds close to native machine code because it is low-level and optimized.
- Security: It runs in a sandboxed execution environment (same as JavaScript).
2. Wasm vs. JavaScript
WebAssembly is not designed to replace JavaScript. It is designed to work alongside JavaScript.
- JavaScript: High-level, dynamic, garbage-collected, flexible. Great for UI, glue code, and interactivity.
- WebAssembly: Low-level, static, linear memory. Great for computationally intensive tasks (math, physics, image processing).
3. How it Works
- Write Code: You write code in a high-performance language (e.g., Rust).
- Compile: You compile that code into a
.wasmbinary file. - Load: Your JavaScript code fetches the
.wasmfile. - Instantiate: The browser instantiates the Wasm module.
- Run: JavaScript calls functions exported by the Wasm module, and Wasm can call imported JavaScript functions.
4. Key Components
- Module: A compiled WebAssembly binary that has been parsed by the browser. It is stateless (like a class).
- Instance: A Module paired with all the state it uses at runtime (like an object).
- Memory: A resizable ArrayBuffer that acts as the linear memory for the Wasm instance. Both JS and Wasm can read/write to this memory.
- Table: A resizable typed array of references (e.g., to functions) that cannot be stored in raw memory for security reasons.
5. Use Cases
- Games: Porting Unity/Unreal Engine games to the web.
- Media Editing: Video editors (Adobe Premiere), Image manipulation (Figma).
- Scientific Simulation: Running complex simulations in the browser.
- Cryptography: Fast encryption/decryption.
6. WASI (WebAssembly System Interface)
WASI is a modular system interface for WebAssembly. It allows Wasm code to run outside the browser (on the server, IoT devices, etc.) in a secure and portable way.
- The Problem: Standard Wasm has no access to the file system, network, or system clock. In the browser, it relies on JavaScript glue code to access these.
- The Solution: WASI provides a standard API (like POSIX) for accessing system resources.
- Security: WASI uses a capability-based security model. A Wasm module cannot open a file unless it is explicitly granted permission to access that specific directory.
- Use Case: Serverless functions, containerization (Wasm containers are lighter/faster than Docker), plugin systems.