在这个基准测试中,Node 怎么这么快?

sha*_*ane 4 javascript node.js rust

为了学习一些系统编程,我打算尝试用 Rust 编写一个标记器。尽管我立即发现它在迭代字符串的字符时非常慢。我整理了一个简单的基准来说明我的意思。

src/bench.html 是一个大约有 3000 个字符的 html 文档

节点:

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

锈:

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!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释我在 rust 示例中做错了什么,使其比 node 中的相同操作慢 10 倍吗?

所有代码都可以在这里找到https://github.com/shakyShane/rust-vs-node

sha*_*ane 5

简单的答案,在进行基准测试时,不要使用,target/debug/program而是cargo build --release先运行。这将为您target/release/program提供基准测试:)