Skip to content

Instantly share code, notes, and snippets.

@mexus
Last active July 5, 2020 13:12
Show Gist options
  • Save mexus/bebacfeffb6468eba7b774c5c0e53538 to your computer and use it in GitHub Desktop.
Save mexus/bebacfeffb6468eba7b774c5c0e53538 to your computer and use it in GitHub Desktop.
benchmark of various concatenation methods of a small and a large strings
// In `Cargo.toml`:
// [dev-dependencies]
// criterion = "0.3.3"
//
// [[bench]]
// name = "concat"
// harness = false
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
pub fn criterion_benchmark(c: &mut Criterion) {
let smol = String::from("123");
let big = vec!["Very large string ahaha"; 100].concat();
let reference = smol.clone() + &big;
let mut group = c.benchmark_group("concatenations");
group.bench_function("concat", |b| {
b.iter(|| {
let concat = [smol.as_str(), big.as_str()].concat();
assert_eq!(concat, reference);
})
});
group.bench_function("push_str", |b| {
b.iter_batched(
|| smol.clone(),
|mut smol| {
smol.push_str(&big);
assert_eq!(smol, reference);
},
BatchSize::SmallInput,
)
});
group.bench_function("add-assign", |b| {
b.iter_batched(
|| smol.clone(),
|mut smol| {
smol += &big;
assert_eq!(smol, reference);
},
BatchSize::SmallInput,
)
});
group.bench_function("format", |b| {
b.iter(|| {
let format = format!("{}{}", smol, big);
assert_eq!(format, reference);
})
});
group.bench_function("µfmt", |b| {
b.iter(|| {
let mut output = String::with_capacity(reference.len());
ufmt::uwrite!(output, "{}{}", smol, big).unwrap();
assert_eq!(output, reference);
})
});
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
@mexus
Copy link
Author

mexus commented Jul 5, 2020

image

@mexus
Copy link
Author

mexus commented Jul 5, 2020

Added µfmt

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment