这是我想在 rust 中翻译以在 wasm 中编译它的原始函数,因为它会使其更快(因为它是我服务器中的热门函数)
export const generateRandomGuid = function (): string {
let guid: string = "0x";
let guidString: string = uuidv4();
const bytes = uuidParse(guidString);
const arrayBytes = new Uint8Array(bytes);
for (let index = 0; index < arrayBytes.length; index++) {
if (guid.length === 18) break;
const byte = arrayBytes[index].toString(16);
if (arrayBytes[index].toString(16).length === 1) {
guid += "0" + byte;
} else {
guid += byte;
}
}
return guid;
};
我在 rust 中这样翻译它:
use uuid::Uuid;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn generate_random_guid() -> String {
let my_uuid: Uuid = Uuid::new_v4();
let array_bytes = my_uuid.as_bytes();
let mut rand_id: String = String::new();
rand_id.push_str("0x");
for byte in array_bytes {
let formatted_byte: String = format!("{:X}", byte);
if formatted_byte.len() == 1 {
let mut formatted_byte_with_additionnal_zero: String = "0".to_string();
formatted_byte_with_additionnal_zero.push_str(&formatted_byte);
rand_id.push_str(&formatted_byte_with_additionnal_zero);
} else {
rand_id.push_str(&formatted_byte);
}
if rand_id.len() == 18 {
break;
}
}
return rand_id;
}
使用 wasm-pack 在 wasm 中编译并使用以下配置:
[package]
name = "h1emu-core"
version = "0.1.4"
edition = "2018"
[dependencies]
wasm-bindgen = "0.2.45"
uuid = {version = "0.8.2", features = ["v4","wasm-bindgen"], default-features = false }
getrandom = { version = "0.2.3", features = ["js"] }
[lib]
crate-type = ["cdylib"]
[profile.release]
lto = true
opt-level = 3
结果不是想要的,似乎 js 版本比 wasm 版本快两倍。所以我问自己是否只是我的 rust 代码不好,或者我的配置,或者就我而言,wasm 不合适。