JavaScript ครองโลก Web มานานหลายทศวรรษ แต่เมื่อ Web Application ต้องทำงานหนักขึ้น ไม่ว่าจะเป็นการตัดต่อวิดีโอ, การ Render กราฟิก 3D หรือการประมวลผล AI Model ใน Browser ข้อจำกัดด้าน Performance ของ JavaScript ก็เริ่มเห็นชัด WebAssembly (Wasm) ถือกำเนิดขึ้นมาเพื่อแก้ปัญหานี้ โดยเป็น Binary Instruction Format ที่ทำงานใกล้เคียง Native Speed บน Browser
บทความนี้จะพาคุณเข้าใจ WebAssembly ตั้งแต่พื้นฐาน การ Compile จากภาษาต่างๆ ไปจนถึงการนำไปใช้นอก Browser ด้วย WASI และ Edge Computing ในปี 2026 สำหรับ Developer ที่กำลัง สอน python หรือเรียนรู้ภาษาอื่นอยู่ WebAssembly เป็นเทคโนโลยีที่ควรรู้จักไว้
WebAssembly คืออะไร?
WebAssembly (Wasm) คือ Binary Instruction Format ที่ออกแบบมาให้เป็น Compilation Target สำหรับภาษาต่างๆ เช่น C, C++, Rust, Go โดยสามารถทำงานใน Web Browser ที่ความเร็วใกล้เคียง Native Code ถูกพัฒนาร่วมกันโดย Mozilla, Google, Microsoft และ Apple ผ่าน W3C WebAssembly Working Group
คุณสมบัติหลักของ WebAssembly
- Fast: ทำงานที่ Near-native Speed เพราะเป็น Binary Format ไม่ต้อง Parse เหมือน JavaScript
- Safe: ทำงานใน Sandboxed Environment มีระบบ Memory Safety
- Portable: ทำงานได้ทุก Platform ที่มี Wasm Runtime (Browser, Server, Edge, IoT)
- Open: เป็นมาตรฐานเปิดของ W3C ทุก Browser หลักรองรับ
- Language Agnostic: Compile ได้จากหลายภาษา ไม่ผูกกับภาษาใดภาษาหนึ่ง
Wasm File Format
# WebAssembly มี 2 Format
# 1. Binary Format (.wasm) — สำหรับ Execution
# 2. Text Format (.wat) — สำหรับอ่าน/Debug (เหมือน Assembly)
# ตัวอย่าง WAT (WebAssembly Text Format)
(module
(func $add (param $a i32) (param $b i32) (result i32)
local.get $a
local.get $b
i32.add
)
(export "add" (func $add))
)
# Compile WAT → WASM
# wat2wasm add.wat -o add.wasm
Wasm vs JavaScript — เปรียบเทียบ Performance
WebAssembly ไม่ได้มาแทน JavaScript แต่มาเสริมในงานที่ต้องการ Performance สูง ลองดูเปรียบเทียบ:
| ด้าน | JavaScript | WebAssembly |
|---|---|---|
| รูปแบบ | Text (Source Code) | Binary (Compiled) |
| การ Parse | ช้ากว่า (ต้อง Parse + Compile) | เร็วกว่า (Decode binary) |
| Execution Speed | JIT Compiled, ปรับแต่ง Runtime | Near-native, Predictable |
| Memory | Garbage Collected | Linear Memory, Manual Management |
| DOM Access | ตรง | ผ่าน JavaScript Interop |
| Development Speed | เร็ว, Ecosystem ใหญ่ | ช้ากว่า, ต้อง Compile |
| Use Case | UI, Business Logic, ทั่วไป | CPU-intensive, Image/Video, Games, AI |
| File Size | ใหญ่กว่า (Text) | เล็กกว่า (Binary Compact) |
Performance Benchmark ตัวอย่าง
// Fibonacci Benchmark: JavaScript vs WebAssembly
// JavaScript
function fibJS(n) {
if (n <= 1) return n;
return fibJS(n - 1) + fibJS(n - 2);
}
console.time('JS Fibonacci(40)');
fibJS(40);
console.timeEnd('JS Fibonacci(40)');
// ผลลัพธ์: ~1,200ms
// WebAssembly (compiled from C)
const wasmInstance = await WebAssembly.instantiateStreaming(
fetch('fib.wasm')
);
console.time('Wasm Fibonacci(40)');
wasmInstance.instance.exports.fib(40);
console.timeEnd('Wasm Fibonacci(40)');
// ผลลัพธ์: ~450ms (~2.7x เร็วกว่า)
// หมายเหตุ: ส่วนต่างจะยิ่งมากในงาน CPU-intensive จริงๆ
// เช่น Image Processing, Compression, Cryptography
Compile ภาษาต่างๆ เป็น WebAssembly
C/C++ ด้วย Emscripten
Emscripten เป็น Toolchain ที่แปลง C/C++ เป็น WebAssembly พร้อม JavaScript Glue Code
# ติดตั้ง Emscripten
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
# เขียน C Code
// hello.c
#include <stdio.h>
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
EMSCRIPTEN_KEEPALIVE
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
printf("Hello from WebAssembly!\n");
return 0;
}
# Compile เป็น Wasm
emcc hello.c -o hello.js -s EXPORTED_FUNCTIONS='["_add","_factorial","_main"]' \
-s EXPORTED_RUNTIME_METHODS='["ccall","cwrap"]' \
-O3
# ผลลัพธ์: hello.js + hello.wasm
<!-- ใช้งานใน HTML -->
<script src="hello.js"></script>
<script>
Module.onRuntimeInitialized = () => {
// เรียกฟังก์ชัน C จาก JavaScript
const add = Module.cwrap('add', 'number', ['number', 'number']);
console.log('3 + 4 =', add(3, 4)); // 7
const factorial = Module.cwrap('factorial', 'number', ['number']);
console.log('10! =', factorial(10)); // 3628800
};
</script>
Rust ด้วย wasm-pack
Rust เป็นภาษาที่เหมาะกับ WebAssembly ที่สุดเพราะมี Memory Safety โดยไม่ต้องใช้ Garbage Collector และมี Ecosystem ที่ดีเยี่ยม
# ติดตั้ง Rust + wasm-pack
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
cargo install wasm-pack
# สร้างโปรเจกต์ Rust สำหรับ Wasm
cargo init --lib wasm-demo
cd wasm-demo
# Cargo.toml
[package]
name = "wasm-demo"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console", "Document", "Element", "HtmlElement", "Window"] }
js-sys = "0.3"
[profile.release]
opt-level = "z" # Optimize for size
lto = true # Link-Time Optimization
codegen-units = 1
// src/lib.rs
use wasm_bindgen::prelude::*;
use web_sys::console;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}! From WebAssembly with Rust", name)
}
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
if n <= 1 {
return n as u64;
}
let mut a: u64 = 0;
let mut b: u64 = 1;
for _ in 2..=n {
let temp = a + b;
a = b;
b = temp;
}
b
}
// Image Processing Example
#[wasm_bindgen]
pub fn grayscale(data: &mut [u8]) {
for pixel in data.chunks_exact_mut(4) {
let avg = ((pixel[0] as u16 + pixel[1] as u16 + pixel[2] as u16) / 3) as u8;
pixel[0] = avg; // R
pixel[1] = avg; // G
pixel[2] = avg; // B
// pixel[3] = alpha (unchanged)
}
}
# Build
wasm-pack build --target web --release
# ผลลัพธ์: pkg/ directory พร้อม .wasm + JS bindings
// ใช้งานใน JavaScript
import init, { greet, fibonacci, grayscale } from './pkg/wasm_demo.js';
async function main() {
await init();
console.log(greet('Developer')); // Hello, Developer! From WebAssembly with Rust
console.log(fibonacci(50)); // 12586269025
// Image Processing
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
grayscale(imageData.data); // แปลงเป็นขาวดำ ด้วย Wasm!
ctx.putImageData(imageData, 0, 0);
}
main();
Go ด้วย TinyGo
# ติดตั้ง TinyGo (Go compiler สำหรับ Wasm ที่สร้าง Binary เล็กกว่า)
# Standard Go: Wasm output ~10MB
# TinyGo: Wasm output ~100KB-1MB
# main.go
package main
import (
"fmt"
"syscall/js"
)
func add(this js.Value, args []js.Value) interface{} {
a := args[0].Int()
b := args[1].Int()
return a + b
}
func main() {
fmt.Println("Go WebAssembly Initialized!")
js.Global().Set("goAdd", js.FuncOf(add))
select {} // Block forever
}
# Compile ด้วย TinyGo
tinygo build -o main.wasm -target wasm ./main.go
# ขนาด: ~200KB (เทียบกับ Go standard: ~10MB)
AssemblyScript — TypeScript-like สำหรับ Wasm
# สำหรับ Developer ที่คุ้นเคย TypeScript
# AssemblyScript ใช้ Syntax คล้าย TypeScript แต่ Compile เป็น Wasm
npm init
npm install --save-dev assemblyscript
npx asinit .
// assembly/index.ts
export function add(a: i32, b: i32): i32 {
return a + b;
}
export function isPrime(n: i32): bool {
if (n < 2) return false;
for (let i: i32 = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
export function countPrimes(limit: i32): i32 {
let count: i32 = 0;
for (let i: i32 = 2; i <= limit; i++) {
if (isPrime(i)) count++;
}
return count;
}
# Build
npm run asbuild
# ใช้งาน
import { add, countPrimes } from "./build/release.js";
console.log(add(1, 2)); // 3
console.log(countPrimes(100000)); // 9592
WebAssembly ใน Browser
การโหลดและ Instantiate Wasm Module
// วิธีที่ 1: Streaming Compilation (แนะนำ)
const { instance, module } = await WebAssembly.instantiateStreaming(
fetch('module.wasm'),
importObject
);
const result = instance.exports.myFunction(42);
// วิธีที่ 2: Manual Loading
const response = await fetch('module.wasm');
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes, importObject);
// วิธีที่ 3: Compile แยก (สำหรับ Cache)
const module = await WebAssembly.compileStreaming(fetch('module.wasm'));
// เก็บ module ไว้ใน IndexedDB สำหรับโหลดครั้งต่อไป
const instance = await WebAssembly.instantiate(module, importObject);
Memory Management
// WebAssembly ใช้ Linear Memory (ArrayBuffer ขนาดใหญ่)
const memory = new WebAssembly.Memory({
initial: 256, // 256 pages = 16MB (1 page = 64KB)
maximum: 1024 // 1024 pages = 64MB
});
// แชร์ Memory ระหว่าง JS กับ Wasm
const importObject = {
env: { memory }
};
// อ่าน/เขียน Memory จาก JavaScript
const view = new Uint8Array(memory.buffer);
view[0] = 42; // เขียนค่าลง Memory
// ส่ง String จาก JS → Wasm (ต้อง Encode)
function passStringToWasm(str, instance) {
const encoder = new TextEncoder();
const encoded = encoder.encode(str);
const ptr = instance.exports.alloc(encoded.length);
const mem = new Uint8Array(instance.exports.memory.buffer);
mem.set(encoded, ptr);
return { ptr, len: encoded.length };
}
JavaScript Interop
// Import JavaScript functions เข้า Wasm
const importObject = {
env: {
// Wasm เรียก JS ได้ผ่าน Import
log_message: (ptr, len) => {
const bytes = new Uint8Array(memory.buffer, ptr, len);
const message = new TextDecoder().decode(bytes);
console.log(message);
},
get_time: () => Date.now(),
random: () => Math.random(),
},
js: {
// DOM Manipulation ผ่าน JS
update_element: (id_ptr, id_len, val_ptr, val_len) => {
const id = decodeString(id_ptr, id_len);
const val = decodeString(val_ptr, val_len);
document.getElementById(id).textContent = val;
}
}
};
// ใช้ wasm-bindgen (Rust) จะจัดการ Interop ให้อัตโนมัติ
// ไม่ต้องจัดการ Memory เอง
WASI — WebAssembly นอก Browser
WASI (WebAssembly System Interface) คือมาตรฐานที่ให้ WebAssembly ทำงานนอก Browser ได้ โดยมี API สำหรับเข้าถึง File System, Network, Environment Variables เป็นต้น ทำให้ Wasm กลายเป็น "Universal Binary" ที่ทำงานได้ทุกที่
# Wasm Runtimes สำหรับ WASI
# 1. Wasmtime (by Bytecode Alliance — Mozilla, Fastly, Intel)
curl https://wasmtime.dev/install.sh -sSf | bash
wasmtime run hello.wasm
# 2. Wasmer
curl https://get.wasmer.io -sSfL | sh
wasmer run hello.wasm
# 3. WasmEdge (optimized for cloud-native)
curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash
wasmedge run hello.wasm
เขียน WASI Application ด้วย Rust
// WASI application — อ่าน/เขียนไฟล์
use std::fs;
use std::io::Write;
fn main() {
// อ่านไฟล์
let content = fs::read_to_string("/data/input.txt")
.expect("Failed to read file");
println!("File content: {}", content);
// เขียนไฟล์
let mut file = fs::File::create("/data/output.txt")
.expect("Failed to create file");
file.write_all(b"Hello from WASI!")
.expect("Failed to write");
// Environment Variables
for (key, value) in std::env::vars() {
println!("{}={}", key, value);
}
// Arguments
let args: Vec = std::env::args().collect();
println!("Args: {:?}", args);
}
# Compile สำหรับ WASI
rustup target add wasm32-wasip1
cargo build --target wasm32-wasip1 --release
# Run ด้วย Wasmtime (กำหนดสิทธิ์เข้าถึง Directory)
wasmtime run --dir /data target/wasm32-wasip1/release/app.wasm
Wasm สำหรับ Edge Computing
Edge Computing คือหนึ่งใน Use Case ที่ทรงพลังที่สุดของ WebAssembly เพราะ Wasm มี Cold Start ที่เร็วมาก (microseconds) และ Binary Size เล็ก เหมาะกับ Edge Environment ที่ต้องการ Low Latency
Cloudflare Workers
# Cloudflare Workers รองรับ Wasm natively
# สร้าง Worker ด้วย Rust + Wasm
# wrangler.toml
name = "my-wasm-worker"
main = "build/worker/shim.mjs"
compatibility_date = "2026-04-10"
[build]
command = "cargo install -q worker-build && worker-build --release"
// src/lib.rs
use worker::*;
#[event(fetch)]
async fn main(req: Request, env: Env, _ctx: Context) -> Result {
let url = req.url()?;
match url.path() {
"/" => Response::ok("Hello from Wasm on the Edge!"),
"/compute" => {
// CPU-intensive work ที่ Wasm ทำได้เร็ว
let result = heavy_computation();
Response::ok(format!("Result: {}", result))
}
_ => Response::error("Not Found", 404),
}
}
fn heavy_computation() -> u64 {
// Image resize, crypto, data transform ฯลฯ
(1..1_000_000u64).filter(|n| is_prime(*n)).count() as u64
}
Fermyon Spin
# Fermyon Spin — Wasm-native serverless platform
# ติดตั้ง
curl -fsSL https://developer.fermyon.com/downloads/install.sh | bash
# สร้าง App
spin new -t http-rust my-spin-app
cd my-spin-app
// src/lib.rs
use spin_sdk::http::{IntoResponse, Request, Response};
use spin_sdk::http_component;
#[http_component]
fn handle_request(req: Request) -> anyhow::Result {
Ok(Response::builder()
.status(200)
.header("content-type", "application/json")
.body(r#"{"message": "Hello from Spin + Wasm!"}"#)
.build())
}
# Build + Run
spin build
spin up
# Server starts in ~1ms!
เปรียบเทียบ Wasm Edge vs Container
| ด้าน | Container (Docker) | Wasm (WASI) |
|---|---|---|
| Cold Start | 100ms - 30s | < 1ms |
| Binary Size | 50MB - 1GB+ | 100KB - 10MB |
| Memory | 50MB+ | < 10MB |
| Isolation | OS-level (namespaces) | Sandbox (capability-based) |
| Portability | Linux x86/ARM | ทุก Platform ที่มี Runtime |
| Security | Root by default (ต้อง Harden) | Deny-by-default (ปลอดภัยกว่า) |
Real-World Wasm Use Cases
WebAssembly ไม่ใช่แค่ Demo หรือ Toy Project หลายบริษัทระดับโลกใช้ Wasm ใน Production จริง:
Figma — Design Tool ใน Browser
Figma ใช้ WebAssembly สำหรับ Rendering Engine ทำให้สามารถ Render กราฟิก 2D ที่ซับซ้อนได้อย่างลื่นไหลใน Browser Performance เทียบเท่า Native App โดยใช้ C++ Compile เป็น Wasm ผ่าน Emscripten
Google Earth
Google Earth Web ใช้ WebAssembly ในการ Render ภาพ 3D ของโลก ทำให้ผู้ใช้สามารถดูภาพถ่ายดาวเทียมในมุมมอง 3D ได้โดยไม่ต้องติดตั้ง Plugin ใดๆ
AutoCAD Web
Autodesk นำ AutoCAD Codebase ที่เขียนด้วย C++ มานานหลายทศวรรษ Compile เป็น WebAssembly ทำให้ผู้ใช้สามารถเปิดและแก้ไขไฟล์ DWG ใน Browser ได้ โดยไม่ต้องเขียน Code ใหม่ทั้งหมด
Unity / Unreal Engine
Game Engine ทั้ง Unity และ Unreal รองรับ WebAssembly เป็น Build Target ทำให้สามารถ Deploy เกมไปยัง Browser ได้โดยตรง
Shopify Functions
Shopify ใช้ WebAssembly ให้ Merchant สามารถเขียน Custom Logic (เช่น Discount Rules, Shipping Logic) ด้วยภาษาอะไรก็ได้ที่ Compile เป็น Wasm แล้ว Run บน Shopify's Edge Infrastructure
ตัวอย่างเพิ่มเติม
| บริษัท/โปรเจกต์ | การใช้งาน Wasm |
|---|---|
| Figma | 2D Rendering Engine |
| Google Earth | 3D Globe Rendering |
| AutoCAD Web | CAD Editor ใน Browser |
| Photoshop Web | Image Editing Engine |
| 1Password | Crypto Operations ใน Browser |
| Lichess | Chess Engine (Stockfish compiled to Wasm) |
| FFmpeg.wasm | Video Transcoding ใน Browser |
| SQLite (sql.js) | SQL Database ใน Browser |
Wasm + AI — รัน ML Models ใน Browser
หนึ่งใน Use Case ที่น่าตื่นเต้นที่สุดของ WebAssembly ในปี 2026 คือการรัน AI/ML Models ใน Browser โดยไม่ต้องส่งข้อมูลไปยัง Server สำหรับคนที่กำลัง สอน python เพื่อทำ AI/ML การรู้จัก Wasm จะช่วยให้ Deploy Model ได้หลากหลายขึ้น
// ตัวอย่าง: รัน ONNX Model ด้วย onnxruntime-web (Wasm backend)
import * as ort from 'onnxruntime-web';
// Configure Wasm backend
ort.env.wasm.numThreads = 4;
ort.env.wasm.simd = true;
async function runInference() {
// โหลด Model
const session = await ort.InferenceSession.create('./model.onnx', {
executionProviders: ['wasm'], // ใช้ Wasm Backend
});
// เตรียม Input
const inputTensor = new ort.Tensor('float32', inputData, [1, 3, 224, 224]);
// Run Inference
const results = await session.run({ input: inputTensor });
const output = results.output.data;
console.log('Prediction:', output);
// ทั้งหมดทำงานใน Browser ไม่มีข้อมูลส่งไป Server!
}
// Use Cases:
// - Image Classification (จำแนกรูปภาพ)
// - Object Detection (ตรวจจับวัตถุ)
// - Text Sentiment (วิเคราะห์ความรู้สึก)
// - Face Detection (ตรวจจับใบหน้า)
// - Speech Recognition (แปลงเสียงเป็นข้อความ)
// ทั้งหมดทำงาน Offline ใน Browser ด้วย Wasm!
Wasm + LLM
# web-llm: รัน LLM ใน Browser ด้วย WebGPU + Wasm
# https://github.com/mlc-ai/web-llm
import * as webllm from "@mlc-ai/web-llm";
const engine = await webllm.CreateMLCEngine("Llama-3-8B-Instruct-q4f16_1-MLC");
const reply = await engine.chat.completions.create({
messages: [{ role: "user", content: "อธิบาย WebAssembly ให้หน่อย" }],
});
console.log(reply.choices[0].message.content);
// LLM ตอบกลับ — ทำงานในเครื่อง ไม่ส่งข้อมูลไปไหน!
WASI Preview 2 และ Component Model
Wasm Component Model
Component Model เป็นมาตรฐานใหม่ที่ทำให้ Wasm Modules สามารถสื่อสารกันได้อย่างมีโครงสร้าง โดยใช้ WIT (WebAssembly Interface Types) เป็นภาษากลางในการกำหนด Interface
# WIT (WebAssembly Interface Types) — ภาษาสำหรับกำหนด Interface
# my-component.wit
package myorg:mylib@1.0.0;
interface image-processor {
record image {
width: u32,
height: u32,
data: list,
}
resize: func(img: image, new-width: u32, new-height: u32) -> image;
grayscale: func(img: image) -> image;
blur: func(img: image, radius: f32) -> image;
}
world my-world {
export image-processor;
}
# Component Model ช่วยให้:
# 1. Module ที่เขียนด้วย Rust สื่อสารกับ Module ที่เขียนด้วย Go ได้
# 2. กำหนด Interface ที่ชัดเจน ตรวจสอบ Type ได้
# 3. Compose หลาย Component เข้าด้วยกันได้
WASI Preview 2
WASI Preview 2 (P2) เป็นเวอร์ชันใหม่ที่เพิ่มความสามารถสำคัญ:
- wasi-http: HTTP Client/Server ที่เป็นมาตรฐาน
- wasi-cli: Command-line Application Support
- wasi-filesystem: File System Access ที่ปลอดภัย
- wasi-sockets: Network Socket Support
- wasi-random: Random Number Generation
- wasi-clocks: Clock/Timer Access
Performance Benchmarks
# Benchmark: Wasm vs Native vs JavaScript
# Task: Image Processing (Resize 4000x3000 → 800x600)
# Results (average of 100 runs):
Native (Rust): 12ms
WebAssembly (Rust): 18ms (1.5x slower than native)
JavaScript (Canvas): 85ms (7x slower than native)
Python (Pillow): 120ms (10x slower than native)
# Task: SHA-256 Hash (1MB data)
Native (Rust): 2.1ms
WebAssembly (Rust): 2.8ms
JavaScript (SubtleCrypto): 3.2ms # ใช้ Browser's native crypto
JavaScript (pure): 45ms
# Task: JSON Parse (10MB file)
Native (Rust serde): 15ms
WebAssembly (Rust): 22ms
JavaScript (JSON.parse): 28ms # V8 optimized อย่างดี
# สรุป: Wasm เร็วกว่า JS 2-10x ขึ้นอยู่กับ Task
# JS ที่มี Browser Optimization (เช่น JSON.parse, SubtleCrypto) อาจใกล้เคียง
อนาคตของ WebAssembly
WebAssembly กำลังพัฒนาอย่างรวดเร็ว มี Proposals ที่น่าจับตามอง:
Proposals ที่กำลังพัฒนา
| Proposal | สถานะ (2026) | คำอธิบาย |
|---|---|---|
| Garbage Collection (GC) | Shipped | รองรับภาษาที่มี GC เช่น Java, Kotlin, Dart โดยตรง |
| Threads | Shipped | Multi-threading ด้วย SharedArrayBuffer |
| SIMD | Shipped | Single Instruction Multiple Data สำหรับ Parallel Processing |
| Exception Handling | Shipped | Try/Catch ใน Wasm โดยตรง |
| Tail Call | Shipped | Tail Call Optimization สำหรับ Functional Languages |
| Component Model | Phase 3 | Inter-module Communication ที่เป็นมาตรฐาน |
| Stack Switching | Phase 2 | Coroutines, Green Threads, Async/Await ใน Wasm |
| Memory64 | Phase 3 | 64-bit Memory Addressing (>4GB) |
Wasm GC — เปิดทางสำหรับภาษาใหม่
# ก่อน GC Proposal:
# ภาษาอย่าง Java, Kotlin, Dart ต้องรวม GC Runtime ใน Wasm Binary
# ทำให้ Binary ใหญ่มาก (10-50MB)
# หลัง GC Proposal:
# ภาษาเหล่านี้ใช้ GC ของ Browser โดยตรง
# Binary เล็กลงเหลือ 100KB-2MB
# ตัวอย่าง: Kotlin/Wasm
# build.gradle.kts
kotlin {
wasmJs {
browser()
}
}
# Dart → Wasm (Flutter Web)
# Flutter 3.22+ รองรับ Compile เป็น Wasm โดยตรง
flutter build web --wasm
Wasm Threads + SIMD
// Threads: Multi-threaded Wasm (SharedArrayBuffer)
// ใช้สำหรับ Parallel Processing เช่น Image/Video Processing
// Rust with Wasm Threads
use rayon::prelude::*;
#[wasm_bindgen]
pub fn parallel_sum(data: &[f64]) -> f64 {
data.par_iter().sum() // ใช้ Rayon สำหรับ Parallel Processing
}
// SIMD: Single Instruction Multiple Data
// ใช้สำหรับ Vector/Matrix Operations
// Rust with SIMD
use std::arch::wasm32::*;
#[wasm_bindgen]
pub fn simd_add(a: &[f32], b: &[f32], result: &mut [f32]) {
for i in (0..a.len()).step_by(4) {
unsafe {
let va = v128_load(a[i..].as_ptr() as *const v128);
let vb = v128_load(b[i..].as_ptr() as *const v128);
let vr = f32x4_add(va, vb);
v128_store(result[i..].as_mut_ptr() as *mut v128, vr);
}
}
}
// SIMD ทำให้ Math Operations เร็วขึ้น 2-4x
เมื่อไหร่ควรใช้ Wasm vs JavaScript
ใช้ WebAssembly เมื่อ:
- ต้องการ Performance สูงสำหรับ CPU-intensive Tasks
- มี Codebase ที่เขียนด้วย C/C++/Rust อยู่แล้ว อยาก Port มา Web
- ต้องการ Consistent Performance (ไม่มี JIT Warmup)
- ทำ Image/Video/Audio Processing ใน Browser
- รัน Game Engine หรือ Physics Simulation
- ทำ Cryptographic Operations
- รัน AI/ML Inference ใน Browser
- ต้องการ Edge Computing ที่ Cold Start เร็วมาก
ใช้ JavaScript เมื่อ:
- ทำ UI/DOM Manipulation
- Business Logic ทั่วไป
- ต้องการ Development Speed สูง
- ใช้ Web APIs เช่น Fetch, LocalStorage, DOM Events
- ต้องการ Ecosystem ขนาดใหญ่ (npm)
- Performance ของ JS เพียงพอแล้ว (ซึ่งเกือบทุกกรณี)
เริ่มต้นกับ WebAssembly
สำหรับ Developer ที่เพิ่งเริ่มต้น แนะนำเส้นทางนี้:
# Roadmap สำหรับเรียนรู้ WebAssembly
Week 1: ทำความเข้าใจพื้นฐาน
- อ่าน MDN WebAssembly docs
- ลอง WAT (Text Format) ง่ายๆ
- ทดลอง WebAssembly.instantiate ใน Browser Console
Week 2: เลือกภาษาและ Toolchain
- Rust + wasm-pack (แนะนำที่สุด)
- หรือ AssemblyScript (ถ้าคุ้น TypeScript)
- หรือ C/C++ + Emscripten (ถ้ามี C/C++ Codebase)
Week 3: สร้าง Project จริง
- Image Processing (grayscale, resize)
- Game of Life (classic Wasm tutorial)
- Markdown Parser
- Hash Function
Week 4: Advanced Topics
- JavaScript Interop
- Memory Management
- Performance Profiling (Chrome DevTools)
- WASI + Server-side Wasm
แหล่งเรียนรู้:
- Rust and WebAssembly Book: rustwasm.github.io/docs/book
- MDN WebAssembly: developer.mozilla.org/en-US/docs/WebAssembly
- AssemblyScript: www.assemblyscript.org
- WASI.dev: wasi.dev
สรุป
WebAssembly เปลี่ยนข้อจำกัดของ Web Platform อย่างสิ้นเชิง จากที่เคยทำได้แค่ JavaScript ตอนนี้คุณสามารถนำโค้ด C++, Rust, Go หรือภาษาอื่นๆ มาทำงานใน Browser ที่ความเร็วใกล้เคียง Native Code ทำให้ Application ที่เคยเป็นไปไม่ได้บน Web กลายเป็นจริง ไม่ว่าจะเป็น CAD Editor, Video Editor, Game Engine หรือ AI Model
แต่ WebAssembly ไม่ได้จำกัดอยู่แค่ Browser อีกต่อไป WASI ทำให้ Wasm ทำงานได้ทุกที่ ตั้งแต่ Server, Edge Computing ไปจนถึง IoT ด้วย Cold Start ที่เร็วกว่า Container หลายเท่า ทำให้ Wasm กลายเป็นตัวเลือกที่น่าสนใจสำหรับ Serverless และ Edge Workloads
สำหรับ devops engineer ไทย และ Web Developer ที่ต้องการเพิ่มทักษะในปี 2026 WebAssembly เป็นเทคโนโลยีที่ควรลงทุนเวลาเรียนรู้ เริ่มจากเลือกภาษาที่คุ้นเคย (Rust แนะนำที่สุดสำหรับ Wasm) ลองสร้างโปรเจกต์เล็กๆ แล้วค่อยๆ ขยายไปสู่ WASI และ Edge Computing อนาคตของ Web คือ WebAssembly และอนาคตนั้นมาถึงแล้ว
