Last active
August 29, 2015 14:05
-
-
Save vks/b1ac7cbf0fbce84191a3 to your computer and use it in GitHub Desktop.
Compare performance of `PhfMap` and `HashMap`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(phase)] | |
extern crate test; | |
#[phase(plugin)] | |
extern crate phf_mac; | |
extern crate phf; | |
use test::Bencher; | |
use std::collections::HashMap; | |
use std::iter::FromIterator; | |
use phf::PhfMap; | |
#[deriving(Show)] | |
pub enum Keyword { | |
LOOP, | |
CONTINUE, | |
BREAK, | |
FN, | |
EXTERN, | |
} | |
static KEYWORDS: PhfMap<&'static str, Keyword> = phf_map! { | |
"loop" => LOOP, | |
"continue" => CONTINUE, | |
"break" => BREAK, | |
"fn" => FN, | |
"extern" => EXTERN, | |
}; | |
static kw_existing: [&'static str, ..5] | |
= ["loop", "continue", "break", "fn", "extern"]; | |
static kw_nonexisting: [&'static str, ..5] | |
= ["goto", "static", "while", "if", "else"]; | |
#[bench] | |
fn phf_find_existing(b: &mut Bencher) { | |
b.iter(|| { | |
for k in kw_existing.iter() { | |
KEYWORDS.find(k); | |
} | |
}); | |
} | |
#[bench] | |
fn phf_find_nonexisting(b: &mut Bencher) { | |
b.iter(|| { | |
for k in kw_nonexisting.iter() { | |
KEYWORDS.find(k); | |
} | |
}); | |
} | |
// Compare to HashMap | |
fn make_keywords() -> HashMap<&'static str, Keyword> { | |
FromIterator::from_iter([ | |
("loop", LOOP), | |
("continue", CONTINUE), | |
("break", BREAK), | |
("fn", FN), | |
("extern", EXTERN), | |
].iter().map(|t| *t) | |
) | |
} | |
#[bench] | |
fn hashmap_find_existing(b: &mut Bencher) { | |
let keywords = make_keywords(); | |
b.iter(|| { | |
for k in kw_existing.iter() { | |
keywords.find(k); | |
} | |
}); | |
} | |
#[bench] | |
fn hashmap_find_nonexisting(b: &mut Bencher) { | |
let keywords = make_keywords(); | |
b.iter(|| { | |
for k in kw_nonexisting.iter() { | |
keywords.find(k); | |
} | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment