WebAssembly Einfuehrung
WebAssembly: Hochperformanter Code im Browser
WebAssembly ermöglicht near-native Performance im Web. Lernen Sie die Grundlagen und Einsatzmöglichkeiten von WASM.
Was ist WebAssembly?
WebAssembly (WASM) ist ein binäres Instruktionsformat für eine stack-basierte virtuelle Maschine. Eigenschaften: - Kompiliertes Binärformat (nicht interpretiert) - Near-native Geschwindigkeit - Läuft in allen modernen Browsern - Sicher (Sandbox) - Kann aus C, C++, Rust, Go kompiliert werden
Vergleich: JavaScript vs WebAssembly
| Aspekt | JavaScript | WebAssembly |
|---|---|---|
| Performance | JIT-kompiliert | Near-native |
| Startup | Schneller (klein) | Langsamer (Parsing) |
| DOM-Zugriff | Direkt | Über JS Bridge |
| Speicher | Garbage Collected | Linear Memory |
| Debugging | Einfach | Komplexer |
Use Cases
# Wann WebAssembly nutzen? ✅ CPU-intensive Berechnungen - Bildverarbeitung - Video-Encoding/Decoding - 3D-Rendering - Physik-Simulationen ✅ Bestehender C/C++/Rust Code - Legacy-Bibliotheken portieren - Spiele-Engines ✅ Kryptographie - Hashing, Verschlüsselung # Wann NICHT? ❌ Einfache DOM-Manipulation ❌ Kleine Scripts ❌ I/O-lastige Operationen
Rust zu WebAssembly
# Rust installieren curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # WASM Target hinzufügen rustup target add wasm32-unknown-unknown # wasm-pack installieren cargo install wasm-pack # Neues Projekt cargo new --lib wasm-example cd wasm-example
// Cargo.toml [package] name = "wasm-example" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2)
}
}
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hallo, {}!", name)
}
# Kompilieren wasm-pack build --target web # Erzeugt: # pkg/ # wasm_example_bg.wasm # wasm_example.js # package.json
Im Browser verwenden
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WASM Demo</title>
</head>
<body>
<script type="module">
import init, { fibonacci, greet } from './pkg/wasm_example.js';
async function run() {
await init();
// Funktionen aufrufen
console.log(greet('Welt')); // "Hallo, Welt!"
console.log(fibonacci(10)); // 55
// Performance-Test
console.time('WASM fibonacci(40)');
console.log(fibonacci(40));
console.timeEnd('WASM fibonacci(40)');
}
run();
</script>
</body>
</html>
AssemblyScript (TypeScript-ähnlich)
# Installation npm init -y npm install --save-dev assemblyscript # Projekt initialisieren npx asinit .
// assembly/index.ts
export function add(a: i32, b: i32): i32 {
return a + b;
}
export function factorial(n: i32): i32 {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
# Kompilieren
npm run asbuild
# Verwendung
import { add, factorial } from './build/release.js';
console.log(add(5, 3)); // 8
console.log(factorial(5)); // 120
WASM mit JavaScript laden (Vanilla)
// Methode 1: fetch + instantiate
async function loadWasm() {
const response = await fetch('module.wasm');
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes);
return instance.exports;
}
// Methode 2: instantiateStreaming (effizienter)
async function loadWasmStreaming() {
const { instance } = await WebAssembly.instantiateStreaming(
fetch('module.wasm')
);
return instance.exports;
}
// Verwendung
const wasm = await loadWasm();
console.log(wasm.add(2, 3));
Speicher teilen zwischen JS und WASM
// WASM Memory erstellen
const memory = new WebAssembly.Memory({
initial: 1, // 1 Page = 64KB
maximum: 10
});
// In WASM importieren
const importObject = {
env: {
memory: memory
}
};
const { instance } = await WebAssembly.instantiateStreaming(
fetch('module.wasm'),
importObject
);
// Daten schreiben
const view = new Uint8Array(memory.buffer);
view[0] = 42;
// WASM kann jetzt auf view[0] zugreifen
Bestehende WASM-Bibliotheken
# Bildverarbeitung npm install @aspect/image # SQL im Browser npm install sql.js # PDF-Generierung npm install @aspect/pdfkit # Video-Processing # ffmpeg.wasm # Kryptographie npm install @aspect/argon2
⚠️ Beachten:
WebAssembly hat keinen direkten DOM-Zugriff. Für UI-Interaktionen müssen Sie über JavaScript gehen. WASM ist optimal für Berechnungen, nicht für DOM-Manipulation.