Skip to main content

jsonsplit/
jsonsplit.rs

1//! Where the time in a JSON response actually goes: building the value, or
2//! writing it out.
3use rustlavel_core::Json;
4use std::time::Instant;
5
6fn build() -> Json {
7    Json::Array(
8        (1..=100i64)
9            .map(|id| {
10                Json::object([
11                    ("id", Json::from(id as f64)),
12                    ("name", Json::from(format!("User {id}"))),
13                    ("email", Json::from(format!("user{id}@example.test"))),
14                    ("active", Json::Bool(id % 2 == 0)),
15                    ("score", Json::from(id as f64 * 1.5)),
16                ])
17            })
18            .collect(),
19    )
20}
21
22fn main() {
23    let rounds = 20_000;
24
25    let t = Instant::now();
26    for _ in 0..rounds {
27        std::hint::black_box(build());
28    }
29    let building = t.elapsed().as_micros() as f64 / 1000.0;
30
31    let tree = build();
32    let t = Instant::now();
33    for _ in 0..rounds {
34        std::hint::black_box(tree.to_string());
35    }
36    let writing = t.elapsed().as_micros() as f64 / 1000.0;
37
38    println!("building the Json tree: {building:8.1} ms");
39    println!("writing it out:         {writing:8.1} ms");
40    println!("building is {:.0}% of the total", 100.0 * building / (building + writing));
41}