|
| 1 | +use rust_data_structures::trie::Trie; |
| 2 | +use std::collections::HashSet; |
| 3 | +use std::hint::black_box; |
| 4 | +use std::time::{Duration, Instant}; |
| 5 | + |
| 6 | +const SIZE: usize = 10_000; |
| 7 | + |
| 8 | +fn main() { |
| 9 | + let words = generate_words(); |
| 10 | + |
| 11 | + println!("trie benchmark (manual, std::time::Instant)"); |
| 12 | + println!("size: {SIZE}"); |
| 13 | + println!("trie lookup: {:?}", bench_trie_lookup(&words)); |
| 14 | + println!("hashset lookup: {:?}", bench_hashset_lookup(&words)); |
| 15 | + println!("trie prefix search: {:?}", bench_trie_prefix_search(&words)); |
| 16 | + println!( |
| 17 | + "sorted vector prefix search: {:?}", |
| 18 | + bench_sorted_vector_prefix_search(&words) |
| 19 | + ); |
| 20 | +} |
| 21 | + |
| 22 | +fn bench_trie_lookup(words: &[String]) -> Duration { |
| 23 | + let mut trie = Trie::new(); |
| 24 | + for word in words { |
| 25 | + trie.insert(word); |
| 26 | + } |
| 27 | + |
| 28 | + let start = Instant::now(); |
| 29 | + for word in words { |
| 30 | + black_box(trie.contains(word)); |
| 31 | + } |
| 32 | + start.elapsed() |
| 33 | +} |
| 34 | + |
| 35 | +fn bench_hashset_lookup(words: &[String]) -> Duration { |
| 36 | + let set = words.iter().collect::<HashSet<_>>(); |
| 37 | + |
| 38 | + let start = Instant::now(); |
| 39 | + for word in words { |
| 40 | + black_box(set.contains(word)); |
| 41 | + } |
| 42 | + start.elapsed() |
| 43 | +} |
| 44 | + |
| 45 | +fn bench_trie_prefix_search(words: &[String]) -> Duration { |
| 46 | + let mut trie = Trie::new(); |
| 47 | + for word in words { |
| 48 | + trie.insert(word); |
| 49 | + } |
| 50 | + |
| 51 | + let start = Instant::now(); |
| 52 | + for prefix in ["course-0", "course-1", "course-9"] { |
| 53 | + black_box(trie.words_with_prefix(prefix)); |
| 54 | + } |
| 55 | + start.elapsed() |
| 56 | +} |
| 57 | + |
| 58 | +fn bench_sorted_vector_prefix_search(words: &[String]) -> Duration { |
| 59 | + let mut sorted = words.to_vec(); |
| 60 | + sorted.sort(); |
| 61 | + |
| 62 | + let start = Instant::now(); |
| 63 | + for prefix in ["course-0", "course-1", "course-9"] { |
| 64 | + let matches = sorted |
| 65 | + .iter() |
| 66 | + .filter(|word| word.starts_with(prefix)) |
| 67 | + .collect::<Vec<_>>(); |
| 68 | + black_box(matches); |
| 69 | + } |
| 70 | + start.elapsed() |
| 71 | +} |
| 72 | + |
| 73 | +fn generate_words() -> Vec<String> { |
| 74 | + (0..SIZE).map(|index| format!("course-{index:05}")).collect() |
| 75 | +} |
0 commit comments