提示:本网站现在为维护调试状态

Getting Started with WebAssembly: Rust to WASM + JS

Choyeon
Choyeon
Sep 1, 2026 1 min read 642 Views
366 words 1,811 chars Updated Nov 8, 2026
Getting Started with WebAssembly: Rust to WASM + JS
Table of contents

For CPU-heavy tasks like image/matrix/crypto in browser, JS hits performance limits. WASM compiles Rust to near-native bytecode running in every modern browser.

Toolchain and Basic Bindings

Install wasm-pack and use #[wasm_bindgen] to export Rust functions callable from JS. Complex structs cross via serde + serde_wasm_bindgen serialization.

use wasm_bindgen::prelude::*;
use serde::{Serialize, Deserialize};
use web_sys::console;

#[derive(Serialize, Deserialize)]
pub struct MatrixResult { rows: usize, cols: usize, data: Vec<f64>, compute_ms: f64 }

#[wasm_bindgen(start)]
pub fn init() {
    console_error_panic_hook::set_once();
    console::log_1(&"[WASM] Matrix module loaded".into());
}

#[wasm_bindgen]
pub fn matrix_multiply(a_ptr: *mut f64, a_rows: usize, a_cols: usize, b_ptr: *mut f64, b_cols: usize) -> JsValue {
    use std::time::Instant;
    let t0 = Instant::now();
    let a = unsafe { std::slice::from_raw_parts(a_ptr, a_rows * a_cols) };
    let b = unsafe { std::slice::from_raw_parts(b_ptr, a_cols * b_cols) };
    let mut c = vec![0.0f64; a_rows * b_cols];
    for i in 0..a_rows {
        for k in 0..a_cols {
            let aik = a[i * a_cols + k];
            let rb = &b[k * b_cols..(k + 1) * b_cols];
            let rc = &mut c[i * b_cols..(i + 1) * b_cols];
            for j in 0..b_cols { rc[j] += aik * rb[j]; }
        }
    }
    let r = MatrixResult { rows: a_rows, cols: b_cols, data: c, compute_ms: t0.elapsed().as_secs_f64() * 1000.0 };
    serde_wasm_bindgen::to_value(&r).unwrap()
}

#[wasm_bindgen]
pub fn fibonacci_iter(n: u32) -> u64 {
    if n <= 1 { return n as u64; }
    let (mut prev, mut curr) = (0u64, 1u64);
    for _ in 2..=n { let next = prev.saturating_add(curr); prev = curr; curr = next; }
    curr
}

#[wasm_bindgen(js_name = "allocateFloat64Array")]
pub fn allocate_f64(len: usize) -> *mut f64 {
    let mut v = Vec::with_capacity(len);
    let p = v.as_mut_ptr();
    std::mem::forget(v);
    p
}

JS Invocation and Memory Sharing

WASM memory is a shared ArrayBuffer; reading/writing through TypedArray views is 10-100x faster than serialization. Allocate from JS into WASM memory then pass pointers/sizes for large data.

Metric Plain JS WASM (Rust) Speedup Best For
Matmul 1024x1024 ~1800ms ~85ms ~21x 3D/Games/AI
Fibonacci(n=40) ~980ms ~8ms ~120x Math workloads
SHA-256 1MB ~42ms ~6ms ~7x Crypto/Checksums

Best Practices

Target compute-heavy loops, not DOM work. Prefer TypedArray memory sharing for large data over serialized parameters. Use wasm-opt on release builds to shrink binary size.

X微博Telegram

About the author

Poll

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

Comments (3)

0 / 3000
AI炼丹学徒
AI炼丹学徒Sep 29, 2026

补充一点:实际使用中如果遇到 MySQL 的 8 小时超时问题,可以在连接串里加 autoReconnect=true 参数,虽然官方不推荐但挺好用的。

画画的小鱼
画画的小鱼fishgallery.artSep 29, 2026

哈哈,楼主的踩坑经历和我一模一样!我当时就是没注意到这个配置,排查了整整两天,看到这篇文章泪目了。

熬夜攻城狮
熬夜攻城狮nightowl.techSep 28, 2026

受益匪浅,感谢大佬分享!

Related posts

Rust Ownership & Borrowing: Lifetimes Explained

Rust Ownership & Borrowing: Lifetimes Explained

Master Rust's most unique concepts: ownership rules, mutable/immutable borrowing constraints, lifetime annotations. Compile-error examples + fixes to think like the Borrow Checker for safe zero-cost code.

1 min read
Linux Performance Tuning: perf, bpftrace & BCC

Linux Performance Tuning: perf, bpftrace & BCC

Tune Linux across CPU/mem/IO/net: perf for CPU sampling, bpftrace one-liners for kernel tracepoints, BCC classics biolatency/offcputime to pinpoint production bottlenecks with real incident methodology.

1 min read
Advanced TypeScript Type Gymnastics

Advanced TypeScript Type Gymnastics

TypeScript's type system rivals a full programming language. This article systematically covers conditional types, mapped types, template literal types, infer inference, recursive types, distributive conditional types, and more. With 15+ real utility type implementations (DeepPartial, PathOf, PickByType, CamelCase, etc.), master solution approaches for type-challenges at intermediate difficulty and above.

1 min read
PostgreSQL Query Optimization Techniques

PostgreSQL Query Optimization Techniques

Master PostgreSQL optimization: EXPLAIN ANALYZE plans, choosing index types (B-tree/GIN/BRIN), updating statistics, tuning joins, and partitioned table design for maximum performance.

1 min read
Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust security model primer: built on "never trust, always verify" and dismantles traditional VPN-equals-trusted perimeter thinking. Six pillars explained — identity (MFA/SAML), device health checks, least-privilege RBAC, microsegmentation mTLS, continuous trust scoring, observable audit trail — with implementation roadmap.

1 min read
Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Systematic test pyramid breakdown: bottom unit tests (many, fast, mock isolated), middle integration tests (real service/db/message interaction), top E2E tests (few, critical user flows). Recommended ratio 70/20/10, with coverage metrics and implementation playbook.

1 min read