Created
August 1, 2023 18:12
-
-
Save ttsugriy/e1e63c07927d8f31e71695a9c617bbf3 to your computer and use it in GitHub Desktop.
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
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(unsafe { | |
// SAFETY: `s` is populated using only valid utf8 characters from `BASE_64` | |
str::from_utf8_unchecked(&s[index..]) | |
}); | |
} | |
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