为什么我的防锈程序比ruby程序慢?

我在Ruby和Rust中编写了一个anagram finder,并且非常惊讶地发现Rust程序几乎比Ruby版本慢2倍。

Ruby版本:

source = ARGV.first sorted_source = source.chars.sort.join anagrams = Hash.new File.open('/usr/share/dict/words') do |f| f.each_line do |l| word = l.chomp sorted_word = word.chars.sort.join if anagrams[sorted_word] anagrams[sorted_word] << word else anagrams[sorted_word] = [word] end end end found = anagrams[sorted_source] puts found 

锈版:

 use std::os; use std::io::{File, BufferedReader}; use std::collections::HashMap; fn main(){ let path = Path::new("/usr/share/dict/words"); match File::open(&path) { Err(e) => println!("Error opening file: {}", e.desc), Ok(f) => { let mut anagrams: HashMap<String, Vec> = HashMap::new(); let mut reader = BufferedReader::new(f); for maybe_line in reader.lines() { let word = maybe_line.unwrap().as_slice().trim_chars('\n').to_string(); let mut chars: Vec = word.as_slice().chars().collect(); chars.sort(); let sorted_word = String::from_chars(chars.as_slice()); if anagrams.contains_key(&sorted_word) { anagrams.get_mut(&sorted_word).push(word); } else { anagrams.insert(sorted_word, vec!(word)); } } let args = os::args(); if args.len() == 2 { let source = args[1].clone(); let mut chars: Vec = source.as_slice().chars().collect(); chars.sort(); let sorted_word = String::from_chars(chars.as_slice()); match anagrams.find(&sorted_word) { Some(anagrams) => println!("{}", anagrams), None => println!("No anagrams found") } } else { println!("Call the app with exactly 1 argument, the word to find anagrams for"); } } } } 

结果:

  time ruby anagram.rb horse horse shoer shore ruby anagram.rb horse 1.69s user 0.12s system 99% cpu 1.812 total time ./anagram horse [horse, shoer, shore] ./anagram horse 3.02s user 0.05s system 99% cpu 3.080 total 

ruby-v
ruby 2.1.3p242(2014-09-19修订版47630)[x86_64-darwin13.0]

生锈 – 逆转
rustc 0.13.0-nightly(172b59abe 2014-10-25 00:32:07 +0000)

Ruby主旨: https : //gist.github.com/Valve/533e0e22ae427d9ce440

生锈要塞: https : //gist.github.com/Valve/834917941b00668478f2

更新:

正如Francis Gagne建议的那样,我用-O标志编译它:

  time ./anagram horse [horse, shoer, shore] ./anagram horse 0.37s user 0.05s system 96% cpu 0.429 total 

这样做速度提高了8倍,但仍然只比ruby版快4倍。 我想现在这是一个文件系统限制。

文件大小为:我机器上的235886行。

如果您使用Cargo,则可以将优化设置为高于-O

在你的Cargo.toml

 [package] name = "anagram" version = "0.1.0" authors = ["Your name here "] [profile.release] opt-level = 3 

并运行Cargo build --release 。 一旦完成运行time ./anagram horse