This question already has an answer here:
I wrote an anagram finder in Ruby and Rust and was very surprised to find that Rust program is almost 2 times slower than 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 (2014-09-19 revision 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 gist: https://gist.github.com/Valve/834917941b00668478f2
UPDATE:
As Francis Gagne suggested, I compiled it with -O flag:
time ./anagram horse
[horse, shoer, shore]
./anagram horse 0.37s user 0.05s system 96% cpu 0.429 total
This did a 8x increase in speed, but still only 4x times faster than ruby version. I guess this is a file system limitation now.
The size of the file is: 235886 lines on my machine.
If you're using Cargo you can set the optimization higher than
-O
.In your
Cargo.toml
.And run
Cargo build --release
. Once that is finished runtime ./anagram horse