Last active
July 5, 2020 13:12
-
-
Save mexus/bebacfeffb6468eba7b774c5c0e53538 to your computer and use it in GitHub Desktop.
benchmark of various concatenation methods of a small and a large strings
This file contains hidden or 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment