Skip to content

Instantly share code, notes, and snippets.

@coolreader18
Last active May 20, 2021 01:30
Show Gist options
  • Save coolreader18/dced3494ab51d81b5dd7759ede844864 to your computer and use it in GitHub Desktop.
Save coolreader18/dced3494ab51d81b5dd7759ede844864 to your computer and use it in GitHub Desktop.
use criterion::*;
use rand::distributions::{Standard, Uniform};
use rand::Rng;
#[inline]
fn len_is_ascii(s: &str) -> usize {
if s.is_ascii() {
s.len()
} else {
s.chars().count()
}
}
#[inline]
fn len_direct(s: &str) -> usize {
s.chars().count()
}
fn make_benches(c: &mut Criterion, name: &str, mut gen_str: impl FnMut(usize) -> String) {
let mut group = c.benchmark_group(name);
for &len in &[10, 100, 1000, 10000, 20000] {
let s = gen_str(len);
let s = s.as_str();
group.bench_function(BenchmarkId::new("with_is_ascii", len), |b| {
b.iter(|| len_is_ascii(black_box(s)))
});
group.bench_function(BenchmarkId::new("no_is_ascii", len), |b| {
b.iter(|| len_direct(black_box(s)))
});
}
}
fn bench_strlens(c: &mut Criterion) {
let mut rng = rand::thread_rng();
let mut gen_str = |n, start, end| {
(&mut rng)
.sample_iter(Uniform::new_inclusive(start, end))
.take(n)
.collect::<String>()
};
make_benches(c, "1byte_strlen", |n| gen_str(n, '\0', '\x7f'));
make_benches(c, "2byte_strlen", |n| gen_str(n, '\u{80}', '\u{7ff}'));
make_benches(c, "3byte_strlen", |n| gen_str(n, '\u{800}', '\u{ffff}'));
make_benches(c, "4byte_strlen", |n| gen_str(n, '\u{10000}', char::MAX));
make_benches(c, "assorted_strlen", |n| {
(&mut rng)
.sample_iter::<char, _>(Standard)
.take(n)
.collect()
});
}
criterion_group!(benches, bench_strlens);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment