Develop

Rust 与 WebAssembly 入门:在浏览器中运行高性能代码

✎ -- 字 🕐 -- 分钟
字号
Rust × WebAssembly 技术探索

为什么 Rust + WASM?

WebAssembly(WASM)允许在浏览器中运行编译型语言编写的代码。Rust 凭借零成本抽象和内存安全,成为 WASM 开发的理想选择。典型应用场景包括:图像处理、游戏引擎、数据加密、科学计算等。

1. 环境搭建

# 安装 Rust 工具链
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 安装 wasm-pack
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

# 创建项目
cargo new --lib wasm-demo
cd wasm-demo

2. 编写 Rust 代码

// src/lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

#[wasm_bindgen]
pub fn mandelbrot(width: u32, height: u32, max_iter: u32) -> Vec {
    let mut pixels = vec![0u8; (width * height * 4) as usize];
    for y in 0..height {
        for x in 0..width {
            let cx = (x as f64 / width as f64) * 3.5 - 2.5;
            let cy = (y as f64 / height as f64) * 2.0 - 1.0;
            
            let mut zx = 0.0;
            let mut zy = 0.0;
            let mut iter = 0;
            
            while zx * zx + zy * zy < 4.0 && iter < max_iter {
                let tmp = zx * zx - zy * zy + cx;
                zy = 2.0 * zx * zy + cy;
                zx = tmp;
                iter += 1;
            }
            
            let idx = ((y * width + x) * 4) as usize;
            let color = (255.0 * (iter as f64 / max_iter as f64)) as u8;
            pixels[idx] = color;
            pixels[idx + 1] = color / 2;
            pixels[idx + 2] = color;
            pixels[idx + 3] = 255;
        }
    }
    pixels
}

3. 配置 wasm-pack

# Cargo.toml
[package]
name = "wasm-demo"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"

4. 构建与集成

# 构建 WASM 包
wasm-pack build --target web

# 在 HTML 中使用
<script type="module">
import init, { fibonacci } from './pkg/wasm_demo.js';
await init();
console.log(fibonacci(40)); // 闪电般快速
</script>

性能对比

计算任务JS (ms)WASM (ms)提升
Fibonacci(40)12003534x
Mandelbrot 800x6008504220x

总结

Rust + WASM 将高性能计算带到了浏览器端。对于计算密集型任务,性能提升可达数十倍。随着 WASM GC 和组件模型的成熟,Rust 在前端领域的前景越来越广阔。