为了学习一些系统编程,我打算尝试在rust中编写一个标记器。尽管我立即发现遍历字符串的char极其缓慢。我整理了一个简单的基准来说明我的意思。
src/bench.html
是一个HTML文档,大约3000个字符
节点:
var input = require('fs').readFileSync('src/bench.html', 'utf8');
var len = input.length;
for(var i = 0; i < 100; i+=1) run();
function run () {
var index = 0;
while (index < len) {
var c = input.charAt(index);
// noop
index++;
}
}
锈:
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// Create a path to the desired file
let path = Path::new("src/bench.html");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let mut file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display,
Error::description(&why)),
Ok(file) => file,
};
// Read the file contents into a string, returns `io::Result<usize>`
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("couldn't read {}: {}", display,
Error::description(&why)),
Ok(_) => {
for x in 1..100 {
for token in s.chars() {
match token {
_ => {
// noop
}
}
}
}
println!("done!");
}
}
}
有人可以在rust示例中解释我做错了什么,使它比节点中的同一件事慢10倍吗?
所有代码都可以在这里找到https://github.com/shakyShane/rust-vs-node
简单的答案,在进行基准测试时,不使用target/debug/program
而是cargo build --release
先运行。这将为您target/release/program
提供基准测试:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句