Why is my rust program slower than the ruby ​​equivalent?

I wrote an anagram finder in Ruby and Rust and was very surprised to find that the Rust program is almost 2 times slower than the Ruby version.

Ruby version:

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 

Rust version:

 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<String>> = 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<char> = 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<char> = 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"); } } } } 

Results:

  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 (version 2014-09-19 47630) [x86_64-darwin13.0]

rustc --version
rustc 0.13.0-nightly (172b59abe 2014-10-25 00:32:07 +0000)

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

Rust: https://gist.github.com/Valve/834917941b00668478f2

UPDATE:

As Francis Gan suggested, I compiled it with the -O flag:

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

This led to an 8-fold increase in speed, but still only 4 times faster than the ruby ​​version. I think now this is a limitation of the file system.

File size: 235886 lines on my machine.

+1
source share
1 answer

If you use Cargo, you can set the optimization above -O .

In your Cargo.toml .

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

And run Cargo build --release . Once this is over, run time ./anagram horse

+3
source

Source: https://habr.com/ru/post/1210841/


All Articles