add benchmark for json str escaping

This commit is contained in:
Conrad Ludgate
2025-07-18 09:38:48 +01:00
parent 8e95455aef
commit 44201814b9
4 changed files with 57 additions and 1 deletions
Generated
+1
View File
@@ -3507,6 +3507,7 @@ dependencies = [
name = "json"
version = "0.1.0"
dependencies = [
"criterion",
"futures",
"itoa",
"ryu",
+1 -1
View File
@@ -9,7 +9,6 @@ regex.workspace = true
bytes.workspace = true
anyhow.workspace = true
crc32c.workspace = true
criterion.workspace = true
once_cell.workspace = true
log.workspace = true
memoffset.workspace = true
@@ -22,6 +21,7 @@ tracing.workspace = true
postgres_versioninfo.workspace = true
[dev-dependencies]
criterion.workspace = true
env_logger.workspace = true
postgres.workspace = true
+5
View File
@@ -10,3 +10,8 @@ itoa = "1"
[dev-dependencies]
futures = "0.3"
criterion.workspace = true
[[bench]]
name = "escape"
harness = false
+50
View File
@@ -0,0 +1,50 @@
use std::hint::black_box;
use criterion::{Bencher, Criterion, criterion_group, criterion_main};
#[derive(Debug)]
#[allow(dead_code)]
struct Foo {
some_field: Bar,
some_other_field: String,
}
#[derive(Debug)]
#[allow(dead_code)]
struct Bar {
nested_fields: String,
some_other_value: i32,
}
pub fn escape(c: &mut Criterion) {
c.bench_function("small", |b| bench_json_encode_inner(b, "object_key"));
c.bench_function("large_fmt", |b| {
let value = Foo {
some_field: Bar {
nested_fields: "could not connect to database, control plane error \"foo bar\""
.to_string()
.to_string(),
some_other_value: -1,
},
some_other_field: "error".to_string(),
};
bench_json_encode_inner(b, format_args!("{:?}", &value));
});
}
criterion_group!(benches, escape);
criterion_main!(benches);
fn bench_json_encode_inner(b: &mut Bencher<'_>, v: impl json::ValueEncoder + Copy) {
let mut output = Vec::new();
// write it once so we don't alloc during the benchmark.
json::ValueSer::new(&mut output).value(black_box(v));
b.iter(|| {
output.clear();
json::ValueSer::new(&mut output).value(black_box(v));
black_box(&output[..]);
});
}