---
id: wiki-2026-0508-webassembly
title: WebAssembly
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [WASM, Wasm, WebAssembly]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [webassembly, wasm, performance, compile-target]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: WASM/Rust/C++
  framework: Web Platform / Wasmtime / WASI
---

# WebAssembly

## 매 한 줄
> **"매 portable binary — near-native speed 의 web"**. WASM 매 stack-based VM 의 bytecode — 모든 browser + Node + Wasmtime 의 실행. 2026 modern state 매 Component Model + WASI Preview 2 + GC + threads + SIMD — 매 server / edge / plugin 의 polyglot runtime.

## 매 핵심

### 매 binary format
- **Module**: types / functions / memory / tables / imports / exports.
- **Linear memory**: single contiguous ArrayBuffer — `i32`/`i64`/`f32`/`f64` + `v128` (SIMD).
- **Stack machine**: structured control flow — `block`/`loop`/`if` + `br`/`br_if`.
- **Validation**: load-time type-check — 매 sandboxed by design.

### 매 toolchain (2026)
- **Rust**: `wasm-bindgen` + `wasm-pack` — 매 web ecosystem 의 dominant.
- **C/C++**: Emscripten / `clang --target=wasm32-wasi`.
- **AssemblyScript**: TypeScript-like → WASM.
- **Go**: TinyGo (small binary) / stdlib (large).
- **Zig / .NET / Kotlin / Swift**: 매 first-class targets.

### 매 응용
1. **CPU-heavy web**: video codec / image processing / crypto / physics.
2. **Edge compute**: Cloudflare Workers / Fastly Compute@Edge — 매 cold-start <1ms.
3. **Plugin systems**: Figma / Shopify Functions / Envoy filters — 매 sandbox.
4. **Server runtime**: Wasmtime / Wasmer — 매 polyglot microservices.

## 💻 패턴

### Rust → WASM 매 wasm-bindgen
```rust
// lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn fib(n: u32) -> u64 {
    let (mut a, mut b) = (0u64, 1u64);
    for _ in 0..n { let c = a + b; a = b; b = c; }
    a
}

#[wasm_bindgen]
pub struct Engine { state: Vec<f32> }

#[wasm_bindgen]
impl Engine {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self { Self { state: vec![0.0; 1024] } }
    pub fn step(&mut self, dt: f32) { for x in &mut self.state { *x += dt; } }
}
```

```bash
wasm-pack build --target web
```

```js
// JS side
import init, { fib, Engine } from './pkg/mylib.js';
await init();
console.log(fib(50));
const e = new Engine();
e.step(0.016);
```

### Streaming instantiate
```js
const { instance } = await WebAssembly.instantiateStreaming(
  fetch('/module.wasm'),
  { env: { log: (x) => console.log(x) } }
);
instance.exports.run();
```

### Linear memory 매 zero-copy
```js
const memory = new WebAssembly.Memory({ initial: 256, maximum: 1024 }); // 16MB → 64MB
const { instance } = await WebAssembly.instantiate(bytes, { env: { memory } });
const view = new Uint8Array(memory.buffer, instance.exports.bufPtr(), 1024);
view.set(imageData); // 매 JS → WASM zero-copy
instance.exports.process();
```

### SIMD 매 v128
```rust
use std::arch::wasm32::*;
#[target_feature(enable = "simd128")]
pub unsafe fn add_v(a: &[f32], b: &[f32], out: &mut [f32]) {
    for i in (0..a.len()).step_by(4) {
        let va = v128_load(a.as_ptr().add(i) as *const v128);
        let vb = v128_load(b.as_ptr().add(i) as *const v128);
        v128_store(out.as_mut_ptr().add(i) as *mut v128, f32x4_add(va, vb));
    }
}
```

### Threads 매 SharedArrayBuffer
```bash
# Build with rayon support
RUSTFLAGS='-C target-feature=+atomics,+bulk-memory' \
  wasm-pack build --target web -- --features parallel
```

```js
// 매 COOP+COEP header 필수
// HTTP: Cross-Origin-Opener-Policy: same-origin
//       Cross-Origin-Embedder-Policy: require-corp
import init, { initThreadPool, parallel_sum } from './pkg/mylib.js';
await init();
await initThreadPool(navigator.hardwareConcurrency);
parallel_sum(bigArray);
```

### Component Model + WASI
```bash
# 매 portable component — host 매 Wasmtime / browser
cargo component build --release
wasmtime serve mycomponent.wasm
```

```wit
// world.wit — 매 interface contract
package my:demo;
world api {
  export greet: func(name: string) -> string;
  import logger: interface { log: func(msg: string); }
}
```

### Edge: Cloudflare Workers
```js
// wrangler.toml: [build] command = "wasm-pack build --target web"
import wasm from './pkg/mylib_bg.wasm';
import { greet } from './pkg/mylib.js';
export default {
  async fetch(req) {
    await initWasm(wasm);
    return new Response(greet('edge'));
  }
};
```

## 매 결정 기준
| 상황 | WASM vs JS |
|---|---|
| Tight numeric loop | WASM 2-5x faster |
| DOM manipulation | JS — WASM 매 boundary cost |
| Large library port (FFmpeg, OpenCV) | WASM |
| <1KB hot path | JS — load + boundary overhead |
| Plugin sandbox | WASM 매 isolation |
| Edge cold-start | WASM — <1ms vs JS 5-50ms |

**기본값**: hot CPU path 의 Rust+wasm-bindgen / 일반 web logic 의 JS.

## 🔗 Graph
- 응용: [[Cloudflare Workers]]
- Adjacent: [[Web Worker (웹 워커)]]

## 🤖 LLM 활용
**언제**: CPU-bound hot path / portable plugin sandbox / edge runtime / large native library port.
**언제 X**: simple business logic — JS 매 충분 / DOM-heavy work / small one-off scripts.

## ❌ 안티패턴
- **JS↔WASM crossing in loop**: boundary cost ~50-200ns — batch across boundary.
- **No streaming compile**: `instantiate(bytes)` 의 main-thread block — `instantiateStreaming` 사용.
- **Memory growth thrash**: pre-size `WebAssembly.Memory.maximum`.
- **String marshalling**: UTF-8 copy 매 expensive — pass pointer+len, decode batch.

## 🧪 검증 / 중복
- Verified (WebAssembly Specification 2.0 / WASI Preview 2 / W3C WebAssembly WG).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — toolchain, SIMD, threads, Component Model, edge patterns |
