Add Go and Rust algorithm benchmarks

This commit is contained in:
2026-11-23 06:57:31 +08:00
commit f026a77a11
14 changed files with 2101 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
# Go 与 Rust 的 WASM 斐波那契对比
运行需要 Node.js、支持 `//go:wasmexport` 的 Go,以及安装了 `wasm32-unknown-unknown` 目标的 Rust。
```sh
rustup target add wasm32-unknown-unknown
sh wasm-fib/run.sh
```
两种语言均用无符号 64 位整数执行递归和迭代。Rust 和 Go 直接导出通过 WASM 的 `i64` 接收和返回 JavaScript BigInt。Go 另提供 `syscall/js` 回调,在测试的小整数范围内通过 JavaScript Number 传参和接收结果。三条路径在同一 Node.js 进程里运行,分别预热后交错采样 7 次,报告每次调用的纳秒中位数。短用例交替输入 n 与 n−1 并校验累计结果,递归用例单次调用并核对结果。恒等函数提供调用接口的基线。计时包含 JS 循环及结果消费,模块加载和实例化均在计时区间外。
脚本比较去掉调试信息后的 WASM 文件大小和 gzip 大小。Go 文件同时包含两种调用接口及 Go 运行时,Rust 文件包含三个直接导出。文件大小统计只计 WASM 文件。
## 本机实测
macOS arm64、Node.js 23.10.0、Go 1.26.3、Rust 1.91.1。短用例单位为纳秒,递归用例单位为毫秒。
| 用例 | 输入 | Rust 直接导出 | Go 直接导出 | Go 回调 |
| --- | --- | ---: | ---: | ---: |
| 恒等函数 | 39 / 40 | 13.23 ns | 13.95 ns | 4,147.67 ns |
| 迭代 | 29 / 30 | 15.01 ns | 41.56 ns | 4,000.00 ns |
| 迭代 | 34 / 35 | 13.61 ns | 47.29 ns | 3,847.31 ns |
| 迭代 | 39 / 40 | 14.21 ns | 53.40 ns | 4,024.27 ns |
| 递归 | 30 | 1.261 ms | 9.570 ms | 9.561 ms |
| 递归 | 35 | 13.733 ms | 106.749 ms | 106.206 ms |
| 递归 | 40 | 154.261 ms | 1,183.769 ms | 1,185.083 ms |
| 文件 | 原始字节 | gzip 字节 |
| --- | ---: | ---: |
| Rust | 364 | 272 |
| Go | 1,928,889 | 580,166 |
迭代版通过 Go 回调调用时,耗时与同接口的恒等函数接近。直接导出将此组 Go 的调用耗时降到几十纳秒。递归版的两个 Go 接口耗时接近,但都和 Rust 相差约 7.7 倍。Rust 的 WASM 汇编把一侧递归改成了循环,Go 的编译输出保留两侧递归以及栈检查。这些是已观察到的代码生成差异,对总耗时的贡献没有分别测量。
原文使用 Intel i9-12900H、Node.js 24.9.0 和 mitata,报告的递归差距约为 2.5–2.8 倍。本机测量采用自带计时脚本,原测试的导出代码和计时脚本未在所给文本中列出,无法核对其具体倍数。
+61
View File
@@ -0,0 +1,61 @@
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const { gzipSync } = require('node:zlib');
const [directory, wasmExec] = process.argv.slice(2);
require(wasmExec);
function load(file, imports) {
const bytes = readFileSync(resolve(directory, file));
const module = new WebAssembly.Module(bytes);
console.log(file, bytes.length, 'bytes, gzip', gzipSync(bytes).length, 'bytes');
return new WebAssembly.Instance(module, imports);
}
function measure(fn, args, count, values) {
let sum = 0;
const start = performance.now();
for (let i = 0; i < count; i++) sum += Number(fn(args[i & 1]));
const elapsed = performance.now() - start;
assert.equal(sum, Math.ceil(count / 2) * values[0] + Math.floor(count / 2) * values[1]);
return elapsed * 1e6 / count;
}
const go = new Go();
const goInstance = load('go.wasm', go.importObject);
go.run(goInstance).catch(error => {
console.error(error);
process.exitCode = 1;
});
const rust = load('rust.wasm', {}).exports;
const goDirect = goInstance.exports;
const goCallback = {
recursive: globalThis.goRecursive,
iterative: globalThis.goIterative,
identity: globalThis.goIdentity,
};
console.log(process.version, process.platform, process.arch);
console.log('case n Rust-direct-ns Go-direct-ns Go-callback-ns');
for (const kind of ['identity', 'iterative', 'recursive']) {
const inputs = kind === 'identity' ? [[40, 40]] : [[30, 832040], [35, 9227465], [40, 102334155]];
const counts = kind === 'recursive' ? [1, 1, 1] : [200000, 200000, 2000];
for (const [n, expected] of inputs) {
const functions = [rust[kind], goDirect[kind], goCallback[kind]];
const directArgs = [BigInt(n), BigInt(n - 1)];
const args = [directArgs, directArgs, [n, n - 1]];
const previous = kind === 'identity' ? n - 1 : { 30: 514229, 35: 5702887, 40: 63245986 }[n];
const values = [expected, previous];
const samples = functions.map(() => []);
functions.forEach((fn, index) => measure(fn, args[index], Math.min(counts[index], 1000), values));
for (let trial = 0; trial < 7; trial++) {
for (let offset = 0; offset < functions.length; offset++) {
const index = (trial + offset) % functions.length;
samples[index].push(measure(functions[index], args[index], counts[index], values));
}
}
const medians = samples.map(values => values.sort((a, b) => a - b)[3].toFixed(2));
console.log(kind, n, ...medians);
}
}
+21
View File
@@ -0,0 +1,21 @@
#[no_mangle]
pub extern "C" fn recursive(n: u64) -> u64 {
if n < 2 {
return n;
}
recursive(n - 1) + recursive(n - 2)
}
#[no_mangle]
pub extern "C" fn iterative(n: u64) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n {
(a, b) = (b, a.wrapping_add(b));
}
a
}
#[no_mangle]
pub extern "C" fn identity(n: u64) -> u64 {
n
}
+38
View File
@@ -0,0 +1,38 @@
package main
import "syscall/js"
//go:wasmexport recursive
func recursive(n uint64) uint64 {
if n < 2 {
return n
}
return recursive(n-1) + recursive(n-2)
}
//go:wasmexport iterative
func iterative(n uint64) uint64 {
var a, b uint64 = 0, 1
for i := uint64(0); i < n; i++ {
a, b = b, a+b
}
return a
}
//go:wasmexport identity
func identity(n uint64) uint64 {
return n
}
func register(name string, fn func(uint64) uint64) {
js.Global().Set(name, js.FuncOf(func(_ js.Value, args []js.Value) any {
return float64(fn(uint64(args[0].Int())))
}))
}
func main() {
register("goRecursive", recursive)
register("goIterative", iterative)
register("goIdentity", identity)
select {}
}
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")"
out=../.build/wasm-fib
mkdir -p "$out"
GOOS=js GOARCH=wasm go build -trimpath -ldflags='-s -w' -o "$out/go.wasm" main.go
rustc --edition 2021 --crate-type cdylib --target wasm32-unknown-unknown \
-C opt-level=3 -C panic=abort -C strip=symbols -o "$out/rust.wasm" fib.rs
node bench.cjs "$out" "$(go env GOROOT)/lib/wasm/wasm_exec.js"