Last active
June 1, 2023 01:21
-
-
Save nyurik/16495ecf3034052803ceb1b26b8ac8a9 to your computer and use it in GitHub Desktop.
Rust format! double referencing performance impact
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
// 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