折腾一下午Rust WASM,结果比js还慢?!

148 阅读1分钟

结果

image.png

内容

构建一个 50w 条数据的大数组,通过id查找。我这里查找数组中的最后一条记录,比较的就是遍历数组的速度。

代码

rust

通过 wasm-pack 构建bundle。通过 vite + vite-plugin-wasm 使用。

#[wasm_bindgen]
pub fn get_index(code: String) -> i64 {
    unsafe {
        if let Some(arr) = &ARR_STORE {
            let i = arr.iter().position(|x| x.code == code);
            return match i {
                Some(index) => index as i64,
                None => -1,
            }
        }
        -1
    }
}

js

const i = HUGE_ARR.findIndex((item) => item.code === target);

结论

js NB!。

浏览器: Microsoft Edge 版本 131.0.2903.112