Skip to content

Instantly share code, notes, and snippets.

@badboy
Created October 1, 2026 18:07
Show Gist options
  • Select an option

  • Save badboy/f33a2867f0bb32105bd14dfa7aa1a9a6 to your computer and use it in GitHub Desktop.

Select an option

Save badboy/f33a2867f0bb32105bd14dfa7aa1a9a6 to your computer and use it in GitHub Desktop.
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
fn format(cat: &str, name: &str) -> String {
format!("{cat}.{name}")
}
fn push(cat: &str, name: &str) -> String {
let mut s = String::new();
s.push_str(cat);
s.push('.');
s.push_str(name);
s
}
fn push_cap(cat: &str, name: &str) -> String {
let mut s = String::with_capacity(1 + cat.len() + name.len());
s.push_str(cat);
s.push('.');
s.push_str(name);
s
}
fn push_array(items: &[&str]) -> String {
let mut s = String::with_capacity(items.into_iter().map(|it| it.len()).sum());
items.into_iter().for_each(|it| s.push_str(it));
s
}
fn push_concat(items: &[&str]) -> String {
items.concat()
}
fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("concats");
group.bench_function("format", |b| {
b.iter(|| format(black_box("abc"), black_box("def")))
});
group.bench_function("concat", |b| {
b.iter(|| push(black_box("abc"), black_box("def")))
});
group.bench_function("push_cap", |b| {
b.iter(|| push_cap(black_box("abc"), black_box("def")))
});
group.bench_function("push_array", |b| {
b.iter(|| push_array(black_box(&["abc", ".", "def"])))
});
group.bench_function("push_concat", |b| {
b.iter(|| push_concat(black_box(&["abc", ".", "def"])))
});
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
[package]
name = "stringconcat-bench"
version = "0.1.0"
edition = "2024"
[dev-dependencies]
criterion = "0.8.2"
[[bench]]
name = "bench"
harness = false
Running benches/bench.rs (target/release/deps/bench-86a27cae1c0ce77d)
concats/format time: [24.377 ns 24.509 ns 24.657 ns]
Found 1 outliers among 100 measurements (1.00%)
1 (1.00%) high mild
concats/concat time: [15.779 ns 15.863 ns 15.947 ns]
Found 1 outliers among 100 measurements (1.00%)
1 (1.00%) high mild
concats/push_cap time: [13.814 ns 13.850 ns 13.886 ns]
Found 3 outliers among 100 measurements (3.00%)
3 (3.00%) high mild
concats/push_array time: [15.853 ns 15.924 ns 15.998 ns]
Found 3 outliers among 100 measurements (3.00%)
1 (1.00%) low mild
2 (2.00%) high mild
concats/push_concat time: [15.396 ns 15.461 ns 15.524 ns]
Found 10 outliers among 100 measurements (10.00%)
4 (4.00%) low mild
6 (6.00%) high mild
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment