|
| 1 | +use criterion::{criterion_group, criterion_main, Criterion}; |
| 2 | + |
| 3 | +fn find_boundary_slow(line: &str, word: &str) -> usize { |
| 4 | + let mut count = 0; |
| 5 | + let word_len = word.len(); |
| 6 | + let mut start_pos = 0; |
| 7 | + while let Some(pos_in_line) = line[start_pos..].find(word) { |
| 8 | + let actual_pos = start_pos + pos_in_line; |
| 9 | + let char_before = if actual_pos > 0 { |
| 10 | + line.chars().nth(actual_pos - 1) |
| 11 | + } else { |
| 12 | + None |
| 13 | + }; |
| 14 | + let char_after = line.chars().nth(actual_pos + word_len); |
| 15 | + |
| 16 | + let is_boundary_before = char_before.is_none_or(|c| !c.is_alphanumeric() && c != '_'); |
| 17 | + let is_boundary_after = char_after.is_none_or(|c| !c.is_alphanumeric() && c != '_'); |
| 18 | + |
| 19 | + if is_boundary_before && is_boundary_after { |
| 20 | + count += 1; |
| 21 | + } |
| 22 | + start_pos = actual_pos + word_len; |
| 23 | + } |
| 24 | + count |
| 25 | +} |
| 26 | + |
| 27 | +fn find_boundary_fast(line: &str, word: &str) -> usize { |
| 28 | + let mut count = 0; |
| 29 | + let word_len = word.len(); |
| 30 | + let mut start_pos = 0; |
| 31 | + while let Some(pos_in_line) = line[start_pos..].find(word) { |
| 32 | + let actual_pos = start_pos + pos_in_line; |
| 33 | + let char_before = if actual_pos > 0 { |
| 34 | + line[..actual_pos].chars().next_back() |
| 35 | + } else { |
| 36 | + None |
| 37 | + }; |
| 38 | + let char_after = line[actual_pos + word_len..].chars().next(); |
| 39 | + |
| 40 | + let is_boundary_before = char_before.is_none_or(|c| !c.is_alphanumeric() && c != '_'); |
| 41 | + let is_boundary_after = char_after.is_none_or(|c| !c.is_alphanumeric() && c != '_'); |
| 42 | + |
| 43 | + if is_boundary_before && is_boundary_after { |
| 44 | + count += 1; |
| 45 | + } |
| 46 | + start_pos = actual_pos + word_len; |
| 47 | + } |
| 48 | + count |
| 49 | +} |
| 50 | + |
| 51 | +fn criterion_benchmark(c: &mut Criterion) { |
| 52 | + let long_line = "let abc = 123; ".repeat(1000); |
| 53 | + let word = "abc"; |
| 54 | + |
| 55 | + c.bench_function("slow", |b| { |
| 56 | + b.iter(|| find_boundary_slow(std::hint::black_box(&long_line), std::hint::black_box(word))) |
| 57 | + }); |
| 58 | + c.bench_function("fast", |b| { |
| 59 | + b.iter(|| find_boundary_fast(std::hint::black_box(&long_line), std::hint::black_box(word))) |
| 60 | + }); |
| 61 | +} |
| 62 | + |
| 63 | +criterion_group!(benches, criterion_benchmark); |
| 64 | +criterion_main!(benches); |
0 commit comments