Aprelius logo
uptime: 00:00:00
WebAssembly

WebAssembly Basics

What is WebAssembly?

Wasm is a low-level language, similar to assembly, that runs in the browser with near native performance.

  • Compilation happens at runtime, on the machine — a source language is compiled into a .wasm file, then the browser compiles that bytecode down to real machine code
  • A .wasm file is just a file loaded by JavaScript, like any other asset — after loading, it's talked to through the WebAssembly JS API (e.g. WebAssembly.instantiate), and its exports are just functions callable from JS
  • Browser needs to be able to read Wasm — most of them do now, but that wasn't so obvious some time ago
  • Source languages: C/C++, Rust, Go, Python, Ruby, and any other language with a WASM compiler backend

Stack-based execution

  • The stack is LIFO — last value pushed is the first one popped
  • Instructions push/pop values off the top of the stack, no register allocation needed — keeps the VM simple
wasm
i32.const 2 ;; push 2
i32.const 3 ;; push 3
i32.mul     ;; pop 2 and 3, multiply, push result
call $log   ;; pop result, print it

;; stack: 6

Compiled example

This C source:

cpp
int test1 = 17;
int test2 = 21;
int sum = test1 * test2;

compiles down to WASM with no multiply instruction at all — the compiler constant-folds 17 * 21 at compile time and just stores the result directly:

wasm
(i32.store
  (local.get $0)
  (i32.const 357) ;; result baked in, no i32.mul anywhere
)

References