From 44201814b9c3fa744670d26abf2271896e15d114 Mon Sep 17 00:00:00 2001 From: Conrad Ludgate Date: Thu, 17 Jul 2025 10:11:30 +0100 Subject: [PATCH] add benchmark for json str escaping --- Cargo.lock | 1 + libs/postgres_ffi/Cargo.toml | 2 +- libs/proxy/json/Cargo.toml | 5 ++++ libs/proxy/json/benches/escape.rs | 50 +++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 libs/proxy/json/benches/escape.rs diff --git a/Cargo.lock b/Cargo.lock index 137b883a6d..c476a00abe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3507,6 +3507,7 @@ dependencies = [ name = "json" version = "0.1.0" dependencies = [ + "criterion", "futures", "itoa", "ryu", diff --git a/libs/postgres_ffi/Cargo.toml b/libs/postgres_ffi/Cargo.toml index d4fec6cbe9..9ef8a5b13f 100644 --- a/libs/postgres_ffi/Cargo.toml +++ b/libs/postgres_ffi/Cargo.toml @@ -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 diff --git a/libs/proxy/json/Cargo.toml b/libs/proxy/json/Cargo.toml index 2f163c141d..a6424f868f 100644 --- a/libs/proxy/json/Cargo.toml +++ b/libs/proxy/json/Cargo.toml @@ -10,3 +10,8 @@ itoa = "1" [dev-dependencies] futures = "0.3" +criterion.workspace = true + +[[bench]] +name = "escape" +harness = false diff --git a/libs/proxy/json/benches/escape.rs b/libs/proxy/json/benches/escape.rs new file mode 100644 index 0000000000..17dfe6b4c5 --- /dev/null +++ b/libs/proxy/json/benches/escape.rs @@ -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[..]); + }); +}