在上一章节中,我们有提到 WebAssembly 比 JavaScript 的性能还要快很多,但始终没有举出一个例子来比较它们实际的性能差异。在这篇文章中,会介绍如何把任意现有的 Rust 函数库编译成 WebAssembly,然后移植到网页浏览器上运行,并且比较 Rust 函数库做出来的 WebAssembly 模块以及原生 JS 模块在网页浏览器上运行的性能差异。
ShortCrypt
ShortCrypt 是笔者开发的跨编程语言的数据加解密函数库,其介绍文章的网址如下:
在本篇文章中,将会尝试把用 Rust 编程语言实作的 ShortCrypt 函数库编译成 WebAssembly 模块,并与用原生 JS 程序实作的 ShortCrypt 一同用 Webpack 打包,直接在网页浏览器上实际测试 Rust-WebAssembly 实作和 JS 实作的性能差异。
ShortCrypt WebAssembly
创建项目目录
要将现有的 Rust 函数库编译成 WebAssembly 模块,不一定需要去修改原本 Rust 函数库程序项目的代码。我们同样可以依照上一章介绍的方式,利用 wasm-pack-template 模板创建出一个新的 Cargo 程序项目,名为 short-crypt-webassembly。
指令如下:
引用 short-crypt 套件(crate)
编辑 Cargo.toml,在 [dependencies] 区块下加上:
引用 serde 框架
为了方便实作,我们会引用 serde 框架来协助处理串行化和反串行化的动作。另外,为了让产生出来的 JS 的胶水代码也能够支持 serde 框架的串行化和反串行化,我们还要使用 serde-wasm-bindgen 套件。
编辑 Cargo.toml,在 [dependencies] 区块下加上:
serde-wasm-bindgen = "*"
Rust 程序实作
由于 #[wasm_bindgen] 属性无法用在非目前这个 crate 底下的结构体、枚举、或是函数、方法,因此我们要另外创建一个 Wrapper 结构体,将 short-crypt 这个 crate 下的 ShortCrypt 结构体包裹起来。
程序如下:
...
#[wasm_bindgen]
pub struct ShortCrypt(short_crypt::ShortCrypt);
接着参考 ShortCrypt 的 API 文档,将想要暴露(export)给 JavaScript 使用的函数、方法写进有套用 #[wasm_bindgen] 属性的 impl 区块中。程序如下:
...
use serde::{Deserialize, Serialize};
...
#[derive(Serialize, Deserialize)]
struct Cipher {
pub base: u8,
pub body: Vec<u8>,
}
#[wasm_bindgen]
impl ShortCrypt {
#[wasm_bindgen(constructor)]
pub fn new(key: &str) -> ShortCrypt {
ShortCrypt(short_crypt::ShortCrypt::new(key))
}
pub fn encrypt_string(&self, plaintext: &str) -> JsValue {
let (base, body) = self.0.encrypt(plaintext);
serde_wasm_bindgen::to_value(&Cipher {
base,
body,
})
.unwrap()
}
pub fn encrypt_binary(&self, plaintext: &[u8]) -> JsValue {
let (base, body) = self.0.encrypt(plaintext);
serde_wasm_bindgen::to_value(&Cipher {
base,
body,
})
.unwrap()
}
pub fn decrypt_to_binary(&self, cipher: JsValue) -> Option<Vec<u8>> {
let cipher: Cipher = serde_wasm_bindgen::from_value(cipher).ok()?;
self.0.decrypt(&(cipher.base, cipher.body)).ok()
}
pub fn decrypt_to_string(&self, cipher: JsValue) -> Option<String> {
let cipher: Cipher = serde_wasm_bindgen::from_value(cipher).ok()?;
match self.0.decrypt(&(cipher.base, cipher.body)) {
Ok(v) => String::from_utf8(v).ok(),
Err(_) => None,
}
}
pub fn encrypt_string_to_url_component(&self, data: &str) -> String {
self.0.encrypt_to_url_component(data)
}
pub fn encrypt_binary_to_url_component(&self, data: &[u8]) -> String {
self.0.encrypt_to_url_component(data)
}
pub fn decrypt_url_component_to_binary(&self, url_component: &str) -> Option<Vec<u8>> {
self.0.decrypt_url_component(url_component).ok()
}
pub fn decrypt_url_component_to_string(&self, url_component: &str) -> Option<String> {
match self.0.decrypt_url_component(url_component) {
Ok(v) => String::from_utf8(v).ok(),
Err(_) => None,
}
}
pub fn encrypt_string_to_qr_code_alphanumeric(&self, data: &str) -> String {
self.0.encrypt_to_qr_code_alphanumeric(data)
}
pub fn encrypt_binary_to_qr_code_alphanumeric(&self, data: &[u8]) -> String {
self.0.encrypt_to_qr_code_alphanumeric(data)
}
pub fn decrypt_qr_code_alphanumeric_to_binary(&self, url_component: &str) -> Option<Vec<u8>> {
self.0.decrypt_qr_code_alphanumeric(url_component).ok()
}
pub fn decrypt_qr_code_alphanumeric_to_string(&self, url_component: &str) -> Option<String> {
match self.0.decrypt_qr_code_alphanumeric(url_component) {
Ok(v) => String::from_utf8(v).ok(),
Err(_) => None,
}
}
}
以上程序中,比较需要特别注意的部份有以下几点:
- Rust 编程语言提供的
i8、u32、f64等基本数据类型(不包括 64 比特和 128 比特的整数)可以直接与 JavaScript 的 Number 类型的值做对应。而String字符串结构体和&str字符串切片则可以直接与 JavaScript 的字符串类型的值做对应。Vec<T>可以直接与 JavaScript 的数组类型的值做对应。 wasm_bindgen提供的JsValue可以与 JavaScript 的任意值做对应。#[wasm_bindgen(constructor)]属性可以用来指定要把哪个关联函数当作是 JavaScript 对象的构造器(constructor)。也就是在 JS 中使用 new 关键字时会调用的函数。- 因为
wasm_bindgen不支持有使用泛型的函数,所以这边把原先有用到泛型的函数拆开来写了(将输入和输出的值分为binary和string版本)。 Option枚举的变体None,对应着 JavaScript 的undefined。
然后您可能还会有一个疑问:为什么这边要使用 JsValue 结构体,怎么不要像以下这样也把 Cipher 结构体加上 #[wasm_bindgen] 属性,使它能够直接被函数回传,或是直接作为函数的参数来传入?
#[wasm_bindgen]
pub struct Cipher {
pub base: u8,
pub body: Vec<u8>,
}
是的,这样的确是非常直觉的作法,但这实际上会让程序编译失败,因为 Vec<T> 并没有实作 Copy 特性,它无法作为 JavaScript 对象的公开(public)字段。
建置项目
写完 Rust 程序后,就可以运行以下指令将它编译成 .wasm 文件,以及产生出相对应的胶水代码!
把 WebAssembly 套用在 HTML 网页
依照上一章介绍的方式,我们可以在 Cargo 程序项目目录中,添加一个 www 目录,并完成基本的 TypeScript+Webpack 程序项目。然后再继续进行下面的修改。
在 www 目录运行以下指令加入 short-crypt 套件:
import { ShortCrypt } from "short-crypt";
import { ShortCrypt as ShortCryptWASM } from "../../pkg/short_crypt_webassembly.js";
const TIMES = 100;
const KEY = "magickey";
const TEXT = "articles";
class BenchResult {
constructor(public readonly result1: string, public readonly result2: string, public readonly duration: number) {
}
printLog() {
console.log((this.duration / TIMES * 1000) + "us", this.result1, this.result2);
}
}
export const benchShortCrypt = () => {
let result1 = "";
let result2 = "";
let duration = 0;
for (let i = 0;i < TIMES;i++) {
const start = performance.now();
const sc = new ShortCrypt(KEY);
result1 = sc.encryptToURLComponent(TEXT);
result2 = sc.encryptToQRCodeAlphanumeric(TEXT);
duration += performance.now() - start;
}
return new BenchResult(result1, result2, duration);
};
export const benchShortCryptWASM = () => {
let result1 = "";
let result2 = "";
let duration = 0;
for (let i = 0;i < TIMES;i++) {
const start = performance.now();
const sc = new ShortCryptWASM(KEY);
result1 = sc.encrypt_string_to_url_component(TEXT);
result2 = sc.encrypt_string_to_qr_code_alphanumeric(TEXT);
duration += performance.now() - start;
}
return new BenchResult(result1, result2, duration);
};
import { benchShortCrypt, benchShortCryptWASM } from "./lib.js";
benchShortCrypt().printLog();
benchShortCryptWASM().printLog();
在 Webpack 的进入点中,我们分别测量了原生 JavaScript 版本的 ShortCrypt 和 WebAssembly 版本的 ShortCrypt 的运行时间。会将结果输出到网页浏览器的主控台(console)中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>ShortCrypt</title>
</head>
<body>
Please see the console.
<script src="./js/bundle.min.js"></script>
</body>
</html>
然后就可以在 www 目录中运行 npm run build:webpack 指令来打包项目。接着再使用 VSCode 的 Live Server 打开 Webpack 输出的 index.html,正常情况下会成功在网页浏览器的主控台输出结果。
在 Firefox 60.7.2esr 上的运行结果如下:
40us 2E87Wx52-Tvo 3BHNNR45XZH8PU
在 Chromium 75.0.3770.90 上的运行结果如下:
24.650000013934914us 2E87Wx52-Tvo 3BHNNR45XZH8PU
由此可知 WebAssembly 版本的 ShortCrypt 的性能大概是原生 JavaScript 版本的 20 倍!
适合或不适合编译成 WebAssembly 的 Rust 程序
WebAssembly 固然强大,但我们并没有办法将所有的 Rust 程序都移植成 WebAssembly 程序。像是若 Rust 程序有用到 C/C++ 函数库,那它就无法被成功编译为 WebAssembly 程序。
在 crates.io 上有很多 Rust 的套件可以取用,其中很适合用于 WebAssembly 的分类有:不使用标准函数库的 no-std、解析数据的 parser-implementations 和 text-processing、让 Rust 语法更方便的 rust-patterns。而有些套件则是原本就专门针对 WebAssembly 来设计,会被分在 wasm。
总结
在这个章节中,我们学习了把现有 Rust 函数库编译为 WebAssembly 程序的方式,并且对于 WebAssembly 的程序的性能有所认识。从下一章节开始,要开始实作大一点的项目,利用 WebAssembly 来高效地操作 HTML 的 Canvas,并使它能与用户交互。
下一章:实作康威生命游戏。
