1use babbel_json::{
12 BufferDestination, BufferSource, ParserConfig,
13 embedded::{ArrayBuilder, ObjectBuilder, memory, sensor},
14 parse, parse_with_config, stringify,
15};
16use std::time::{Duration, Instant};
17
18struct BenchmarkResult {
20 name: String,
21 duration: Duration,
22 iterations: u32,
23 ops_per_sec: f64,
24 memory_estimate: Option<usize>,
25}
26
27impl BenchmarkResult {
28 fn new(name: String, duration: Duration, iterations: u32) -> Self {
29 let ops_per_sec = iterations as f64 / duration.as_secs_f64();
30 Self {
31 name,
32 duration,
33 iterations,
34 ops_per_sec,
35 memory_estimate: None,
36 }
37 }
38
39 #[allow(dead_code)]
40 fn with_memory(mut self, bytes: usize) -> Self {
41 self.memory_estimate = Some(bytes);
42 self
43 }
44}
45
46fn main() {
47 println!("=== JSON Library Performance Benchmarks ===\n");
48 println!("Running benchmarks...\n");
49
50 println!("--- Parsing Benchmarks ---");
52 bench_parse_small();
53 bench_parse_medium();
54 bench_parse_large();
55 bench_parse_nested();
56 println!();
57
58 println!("--- Parser Config Benchmarks ---");
60 bench_config_default();
61 bench_config_strict();
62 bench_config_unlimited();
63 println!();
64
65 println!("--- Construction Benchmarks ---");
67 bench_construct_object();
68 bench_construct_array();
69 bench_construct_sensor();
70 println!();
71
72 println!("--- Stringify Benchmarks ---");
74 bench_stringify_small();
75 bench_stringify_medium();
76 bench_stringify_large();
77 println!();
78
79 println!("--- Memory Benchmarks ---");
81 bench_memory_small();
82 bench_memory_medium();
83 bench_memory_large();
84 println!();
85
86 println!("Benchmarks complete!");
87}
88
89fn bench_parse_small() {
91 let json = r#"{"id":"sensor_01","value":23.5,"timestamp":1234567890}"#;
92 let result = benchmark_parse("Parse Small JSON (50 bytes)", json, 50_000);
93 print_result(&result);
94}
95
96fn bench_parse_medium() {
98 let json = r#"
99 {
100 "device": "sensor_01",
101 "location": "room_A",
102 "readings": [
103 {"sensor": "temp", "value": 23.5, "unit": "C"},
104 {"sensor": "humidity", "value": 45.2, "unit": "%"},
105 {"sensor": "pressure", "value": 1013.25, "unit": "hPa"}
106 ],
107 "metadata": {
108 "firmware": "v2.1.0",
109 "battery": 85,
110 "signal": -67
111 },
112 "timestamp": 1234567890
113 }
114 "#;
115 let result = benchmark_parse("Parse Medium JSON (500 bytes)", json, 10_000);
116 print_result(&result);
117}
118
119fn bench_parse_large() {
121 let json = format!(
122 r#"{{
123 "device": "sensor_01",
124 "batch": [{}]
125 }}"#,
126 (0..50)
127 .map(|i| {
128 format!(
129 r#"{{"id":"reading_{}","temp":23.5,"humidity":45.2,"ts":{}}}"#,
130 i,
131 1234567890 + i
132 )
133 })
134 .collect::<Vec<_>>()
135 .join(",")
136 );
137 let result = benchmark_parse("Parse Large JSON (2KB)", &json, 5_000);
138 print_result(&result);
139}
140
141fn bench_parse_nested() {
143 let json = r#"{"a":{"b":{"c":{"d":{"e":{"f":{"g":{"h":"value"}}}}}}}}"#;
144 let result = benchmark_parse("Parse Nested JSON (8 levels)", json, 20_000);
145 print_result(&result);
146}
147
148fn bench_config_default() {
150 let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
151 let config = ParserConfig::new();
152 let result = benchmark_parse_with_config("Parse with Default Config", json, &config, 30_000);
153 print_result(&result);
154}
155
156fn bench_config_strict() {
158 let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
159 let config = ParserConfig::strict();
160 let result = benchmark_parse_with_config("Parse with Strict Config", json, &config, 30_000);
161 print_result(&result);
162}
163
164fn bench_config_unlimited() {
166 let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
167 let config = ParserConfig::unlimited();
168 let result = benchmark_parse_with_config("Parse with Unlimited Config", json, &config, 30_000);
169 print_result(&result);
170}
171
172fn bench_construct_object() {
174 let iterations = 100_000;
175 let start = Instant::now();
176
177 for _ in 0..iterations {
178 let _node = ObjectBuilder::with_capacity(5)
179 .add_str("id", "sensor_01")
180 .add_f64("value", 23.5)
181 .add_i64("timestamp", 1234567890)
182 .add_bool("enabled", true)
183 .add_null("error")
184 .build();
185 }
186
187 let duration = start.elapsed();
188 let result = BenchmarkResult::new(
189 "Construct Object (5 fields)".to_string(),
190 duration,
191 iterations,
192 );
193 print_result(&result);
194}
195
196fn bench_construct_array() {
198 let iterations = 100_000;
199 let start = Instant::now();
200
201 for _ in 0..iterations {
202 let _node = ArrayBuilder::with_capacity(10)
203 .add_i32(1)
204 .add_i32(2)
205 .add_i32(3)
206 .add_i32(4)
207 .add_i32(5)
208 .add_i32(6)
209 .add_i32(7)
210 .add_i32(8)
211 .add_i32(9)
212 .add_i32(10)
213 .build();
214 }
215
216 let duration = start.elapsed();
217 let result = BenchmarkResult::new(
218 "Construct Array (10 elements)".to_string(),
219 duration,
220 iterations,
221 );
222 print_result(&result);
223}
224
225fn bench_construct_sensor() {
227 let iterations = 100_000u32;
228 let start = Instant::now();
229
230 for i in 0..iterations {
231 let _reading =
232 sensor::simple_reading("temp_01", 23.5 + (i as f64 * 0.01), 1234567890 + (i as i64));
233 }
234
235 let duration = start.elapsed();
236 let result = BenchmarkResult::new("Construct Sensor Reading".to_string(), duration, iterations);
237 print_result(&result);
238}
239
240fn bench_stringify_small() {
242 let node = ObjectBuilder::with_capacity(3)
243 .add_str("id", "s1")
244 .add_i32("value", 42)
245 .add_i64("ts", 1234567890)
246 .build();
247
248 let iterations = 50_000;
249 let start = Instant::now();
250
251 for _ in 0..iterations {
252 let mut dest = BufferDestination::new();
253 stringify(&node, &mut dest).unwrap();
254 }
255
256 let duration = start.elapsed();
257 let result = BenchmarkResult::new("Stringify Small Object".to_string(), duration, iterations);
258 print_result(&result);
259}
260
261fn bench_stringify_medium() {
263 let readings = ArrayBuilder::with_capacity(3)
264 .add_node(sensor::simple_reading("temp", 23.5, 1234567890))
265 .add_node(sensor::simple_reading("humidity", 45.2, 1234567891))
266 .add_node(sensor::simple_reading("pressure", 1013.25, 1234567892))
267 .build();
268
269 let node = ObjectBuilder::with_capacity(3)
270 .add_str("device", "sensor_01")
271 .add_node("readings", readings)
272 .add_i64("timestamp", 1234567890)
273 .build();
274
275 let iterations = 10_000;
276 let start = Instant::now();
277
278 for _ in 0..iterations {
279 let mut dest = BufferDestination::new();
280 stringify(&node, &mut dest).unwrap();
281 }
282
283 let duration = start.elapsed();
284 let result = BenchmarkResult::new("Stringify Medium Object".to_string(), duration, iterations);
285 print_result(&result);
286}
287
288fn bench_stringify_large() {
290 let mut readings = Vec::new();
291 for i in 0..50 {
292 readings.push(sensor::simple_reading(
293 "sensor",
294 23.5 + (i as f64 * 0.1),
295 1234567890 + i,
296 ));
297 }
298 let node = sensor::batch_readings("device_01", readings);
299
300 let iterations = 2_000;
301 let start = Instant::now();
302
303 for _ in 0..iterations {
304 let mut dest = BufferDestination::new();
305 stringify(&node, &mut dest).unwrap();
306 }
307
308 let duration = start.elapsed();
309 let result = BenchmarkResult::new("Stringify Large Batch".to_string(), duration, iterations);
310 print_result(&result);
311}
312
313fn bench_memory_small() {
315 let node = ObjectBuilder::with_capacity(3)
316 .add_str("id", "sensor_01")
317 .add_f64("value", 23.5)
318 .add_i64("ts", 1234567890)
319 .build();
320
321 let size = memory::estimate_node_size(&node);
322 println!("Small Object Memory: {} bytes", size);
323}
324
325fn bench_memory_medium() {
327 let node = sensor::multi_reading(
328 "sensor_01",
329 &[
330 ("temperature", 23.5),
331 ("humidity", 45.2),
332 ("pressure", 1013.25),
333 ],
334 1234567890,
335 );
336
337 let size = memory::estimate_node_size(&node);
338 println!("Medium Sensor Reading: {} bytes", size);
339}
340
341fn bench_memory_large() {
343 let mut readings = Vec::new();
344 for i in 0..50 {
345 readings.push(sensor::simple_reading("sensor", 23.5, 1234567890 + i));
346 }
347 let node = sensor::batch_readings("device_01", readings);
348
349 let size = memory::estimate_node_size(&node);
350 println!("Large Batch (50 readings): {} bytes", size);
351}
352
353fn benchmark_parse(name: &str, json: &str, iterations: u32) -> BenchmarkResult {
356 let start = Instant::now();
357
358 for _ in 0..iterations {
359 let mut source = BufferSource::new(json.as_bytes());
360 let _ = parse(&mut source).unwrap();
361 }
362
363 let duration = start.elapsed();
364 BenchmarkResult::new(name.to_string(), duration, iterations)
365}
366
367fn benchmark_parse_with_config(
368 name: &str,
369 json: &str,
370 config: &ParserConfig,
371 iterations: u32,
372) -> BenchmarkResult {
373 let start = Instant::now();
374
375 for _ in 0..iterations {
376 let mut source = BufferSource::new(json.as_bytes());
377 let _ = parse_with_config(&mut source, config).unwrap();
378 }
379
380 let duration = start.elapsed();
381 BenchmarkResult::new(name.to_string(), duration, iterations)
382}
383
384fn print_result(result: &BenchmarkResult) {
385 println!("{}", result.name);
386 println!(" Iterations: {}", result.iterations);
387 println!(" Duration: {:.3}s", result.duration.as_secs_f64());
388 println!(" Throughput: {:.0} ops/sec", result.ops_per_sec);
389 if let Some(mem) = result.memory_estimate {
390 println!(" Memory: {} bytes", mem);
391 }
392 println!();
393}