Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created July 31, 2023 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttsugriy/ed14860ef597ab315d4129d5f8adb191 to your computer and use it in GitHub Desktop.
Save ttsugriy/ed14860ef597ab315d4129d5f8adb191 to your computer and use it in GitHub Desktop.
use criterion::{criterion_group, criterion_main, Criterion};
use std::str;
pub const MAX_BASE: usize = 64;
pub const ALPHANUMERIC_ONLY: usize = 62;
pub const CASE_INSENSITIVE: usize = 36;
const BASE_64: &[u8; MAX_BASE] =
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
#[inline]
pub fn push_str(mut n: u128, base: usize, output: &mut String) {
debug_assert!(base >= 2 && base <= MAX_BASE);
let mut s = [0u8; 128];
let mut index = 0;
let base = base as u128;
loop {
s[index] = BASE_64[(n % base) as usize];
index += 1;
n /= base;
if n == 0 {
break;
}
}
s[0..index].reverse();
output.push_str(str::from_utf8(&s[0..index]).unwrap());
}
#[inline]
pub fn push_str2(mut n: u128, base: usize, output: &mut String) {
debug_assert!(base >= 2 && base <= MAX_BASE);
let mut s = [0u8; 128];
let mut index = s.len();
let base = base as u128;
loop {
index -= 1;
s[index] = BASE_64[(n % base) as usize];
n /= base;
if n == 0 {
break;
}
}
output.push_str(str::from_utf8(&s[index..]).unwrap());
}
fn bench_push_str(c: &mut Criterion) {
let mut group = c.benchmark_group("push_str");
let xs = [0, 1, 35, 36, 37, u64::MAX as u128, u128::MAX];
group.bench_function("old", |b| {
b.iter(|| {
let mut total = 0;
let mut s = String::new();
for base in 2..37 {
for n in xs {
s.clear();
push_str(n, base, &mut s);
total += s.len();
}
}
total
})
});
group.bench_function("new", |b| {
b.iter(|| {
let mut total = 0;
let mut s = String::new();
for base in 2..37 {
for n in xs {
s.clear();
push_str2(n, base, &mut s);
total += s.len();
}
}
total
})
});
group.finish();
}
criterion_group!(benches, bench_push_str);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment