Skip to content

Instantly share code, notes, and snippets.

@nyurik
Last active June 1, 2023 01:21
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 nyurik/16495ecf3034052803ceb1b26b8ac8a9 to your computer and use it in GitHub Desktop.
Save nyurik/16495ecf3034052803ceb1b26b8ac8a9 to your computer and use it in GitHub Desktop.
Rust format! double referencing performance impact
// Place this page as /benches/format.rs in a rust project created with `cargo new fmttest --lib`
// Add to Cargo.toml:
//
// [dev-dependencies]
// criterion = { version = "0.4", features = ["html_reports"] }
//
// [[bench]]
// name = "format"
// harness = false
// To benchmark: cargo bench
// To view html: open target/criterion/report/index.html
use criterion::{criterion_group, criterion_main, Criterion};
use std::fmt::Write;
const ELEMENTS: usize = 100;
pub fn bench_format(c: &mut Criterion) {
let mut buffer = String::with_capacity(ELEMENTS * 10);
let mut g = c.benchmark_group("Summary");
let i = 100;
g.bench_function("value", |b| {
b.iter(|| {
buffer.clear();
for i in 0..ELEMENTS {
_ = write!(buffer, "{}", i);
}
})
});
g.bench_function("reference", |b| {
b.iter(|| {
buffer.clear();
for i in 0..ELEMENTS {
_ = write!(buffer, "{}", &i);
}
})
});
g.finish();
}
criterion_group!(benches, bench_format);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment