最近在写 Flutter 应用,发现 Dart 解析比较大的 json 比较慢,会影响 UI 线程,使用 compute 的话,的确不影响 UI 线程了,但是解析起来更慢,想着可以使用 flutter rust bridge 做个 json 解析库,不过我用 rust 写个测试程序,发现解析 json 比 dart 快不了多少,各位有啥好意见没?
各语言测试:
time node index.js 1.37s user 0.19s system 121% cpu 1.282 total time go build && ./main 1.59s user 0.02s system 80% cpu 2.002 total time python3.9 main.py 2.45s user 0.27s system 98% cpu 2.762 total time cargo run --release 2.46s ser 0.42s system 97% cpu 2.972 total time dart compile exe main.dart && bin/main 4.62s user 0.45s system 114% cpu 4.415 total rust code:
use std::fs::File; use std::io::{Read}; use serde_json::Value; fn parse_json(contents: Vec<u8>) { let now = std::time::Instant::now(); let _: Value = serde_json::from_slice(&contents).unwrap(); let elapsed = now.elapsed(); println!("elapsed: {:?}", elapsed); } fn main() { let cOntents= { let mut vec = Vec::new(); // https://github.com/json-iterator/test-data/blob/master/large-file.json File::open("large-file.json").unwrap().read_to_end(&mut vec).unwrap(); vec }; for _ in 0..10 { parse_json(contents.clone()); } } 测试机器:MacBook Pro (16-inch, 2019) 2.3 GHz 八核 Intel Core i9 32 GB 2667 MHz DDR4
