Merge pull request #207 from rdbtCVS/perf/slice-large-json-20261014

perf(client): parse large fact JSON from in-memory bytes
This commit is contained in:
Ludovic Marie
2026-10-15 01:17:38 +02:00
committed by GitHub
4 changed files with 208 additions and 7 deletions
@@ -0,0 +1,124 @@
//! Compare the read + Value parse stages in BlockFacts::load and Assets::load.
//! Usage: json_load_bench RESOURCE_ROOT [REPETITIONS]; see tools/json_load_fixtures.py.
use serde_json::Value;
use std::{
fs::{self, File},
hint::black_box,
io::BufReader,
path::Path,
time::{Duration, Instant},
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn reader(path: &Path) -> Result<Value> {
Ok(serde_json::from_reader(BufReader::new(File::open(path)?))?)
}
fn slice(path: &Path) -> Result<Value> {
Ok(serde_json::from_slice(&fs::read(path)?)?)
}
fn measure(path: &Path, load: fn(&Path) -> Result<Value>) -> Result<Duration> {
let start = Instant::now();
let value = black_box(load(black_box(path))?);
let elapsed = start.elapsed();
// Value destruction is excluded; the temporary byte buffer is released by slice().
drop(value);
Ok(elapsed)
}
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let root = args
.next()
.ok_or("usage: json_load_bench ROOT [REPETITIONS]")?;
let repetitions: usize = args.next().map_or(Ok(15), |s| s.parse())?;
if repetitions == 0 {
return Err("REPETITIONS must be positive".into());
}
for name in ["gameplay-facts.json", "facts.json"] {
let path = Path::new(&root).join(name);
// Validate complete parsed trees on the exact files being timed.
assert_eq!(reader(&path)?, slice(&path)?);
for _ in 0..2 {
measure(&path, reader)?;
measure(&path, slice)?;
}
let (mut before, mut after) = (Vec::new(), Vec::new());
for i in 0..repetitions {
// Alternate order to reduce filesystem cache / frequency bias.
if i % 2 == 0 {
before.push(measure(&path, reader)?);
after.push(measure(&path, slice)?);
} else {
after.push(measure(&path, slice)?);
before.push(measure(&path, reader)?);
}
}
before.sort_unstable();
after.sort_unstable();
let median = |samples: &[Duration]| {
(samples[(samples.len() - 1) / 2].as_secs_f64()
+ samples[samples.len() / 2].as_secs_f64())
* 500.0
};
let (before, after) = (median(&before), median(&after));
println!(
"{name}: {} bytes; {repetitions} samples; reader {before:.3} ms; slice {after:.3} ms; {:.2}x",
fs::metadata(&path)?.len(),
before / after
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reader_and_slice_preserve_values_and_error_categories() -> Result<()> {
let path =
std::env::temp_dir().join(format!("horizon-json-load-{}.json", std::process::id()));
let check = || -> Result<()> {
fs::write(
&path,
br#"{"states":[{"id":0,"hardness":-1.5,"name":"escaped\n\u2603","outline":[[0,0,0,1,1,1]],"enabled":true}],"defaults":null}"#,
)?;
assert_eq!(reader(&path)?, slice(&path)?);
for invalid in [
&b"{\"states\":["[..],
&b"{\"states\":tru}"[..],
&b"{} trailing"[..],
&b"{\"name\":\"\xff\"}"[..],
] {
fs::write(&path, invalid)?;
let before = reader(&path).unwrap_err();
let after = slice(&path).unwrap_err();
assert_eq!(
before
.downcast_ref::<serde_json::Error>()
.unwrap()
.classify(),
after
.downcast_ref::<serde_json::Error>()
.unwrap()
.classify()
);
}
fs::remove_file(&path)?;
for load in [reader, slice] {
let error = load(&path).unwrap_err();
assert_eq!(
error.downcast_ref::<std::io::Error>().unwrap().kind(),
std::io::ErrorKind::NotFound
);
}
Ok(())
};
let result = check();
let _ = fs::remove_file(path);
result
}
}
+2 -3
View File
@@ -9,7 +9,7 @@ use horizon_world::{
use serde_json::Value;
use std::{
collections::BTreeSet,
fs::File,
fs::{self, File},
io::{self, BufReader},
path::Path,
sync::Arc,
@@ -97,8 +97,7 @@ impl Assets {
if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) {
return Err(invalid("resources do not match Horizon's pinned data version").into());
}
let facts: Value =
serde_json::from_reader(BufReader::new(File::open(root.join("facts.json"))?))?;
let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?;
let states = facts["states"]
.as_array()
.ok_or_else(|| invalid("missing registry state facts"))?;
+8 -4
View File
@@ -3,7 +3,13 @@
use crate::Result;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{collections::HashMap, fs::File, io::BufReader, path::Path, sync::Arc};
use std::{
collections::HashMap,
fs::{self, File},
io::BufReader,
path::Path,
sync::Arc,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderShape {
@@ -106,9 +112,7 @@ pub struct BlockFacts {
}
impl BlockFacts {
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let raw: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("gameplay-facts.json"),
)?))?;
let raw: Value = serde_json::from_slice(&fs::read(root.join("gameplay-facts.json"))?)?;
let entries = raw["states"]
.as_array()
.ok_or("missing gameplay state facts")?;
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Generate schema-shaped synthetic JSON for json_load_bench (not vanilla exports).
Usage: python3 tools/json_load_fixtures.py OUTPUT_DIRECTORY
Targets match the reported production file sizes in decimal MB. Fields mirror
VanillaGameplayFactsExporter and VanillaHeightmapOracle; values/shapes/state
distribution are synthetic. These fixtures measure parsing, not registry validity.
"""
import json
from pathlib import Path
import sys
def gameplay(i):
solid = i % 4 != 0
boxes = [[0.0, 0.0, 0.0, 1.0, (j + 1) / 4, 1.0] for j in range(i % 4)]
edges = []
for axis in range(3):
for u, v in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]:
start = [0.0] * 3
start[(axis + 1) % 3], start[(axis + 2) % 3] = u, v
end = start.copy()
end[axis] = 1.0
edges.append(start + end)
return dict(
id=i, emission=i % 16, dampening=15 if solid else 0,
skylight_down=not solid, shape_occlusion=not solid, can_occlude=solid,
solid_render=solid, hardness=(i % 20) / 4, requires_tool=solid,
replaceable=not solid, random_ticks=i % 3 == 0, block_entity=i % 5 == 0,
render_shape="MODEL", liquid=False, ignited_by_lava=not solid,
push="NORMAL", offset=not solid, full_collision=solid, map_color=8368696,
outline_offset=not solid, outline=boxes, outline_edges=edges,
friction=0.6, speed_factor=1.0, jump_factor=1.0, explosion_resistance=6.0,
item=f"minecraft:fixture_{i % 128}",
sound=dict(volume=1.0, pitch=1.0, **{
event: {"id": f"minecraft:block.stone.{event}"}
for event in ["break", "step", "place", "hit", "fall"]
}),
)
def facts(i):
name = f"minecraft:fixture_{i // 16}"
properties = dict(facing=["north", "south", "east", "west"][i % 4],
level=str(i % 16), waterlogged=str(i % 2 == 0).lower())
description = name + "[" + ",".join(f"{k}={v}" for k, v in properties.items()) + "]"
return [name, False, i % 2 == 0, description,
dict(Name=name, Properties=properties)]
def write(path, target, entry, defaults=False):
with path.open("wb") as output:
output.write(b'{"states":[')
count = 0
while output.tell() < target:
if count:
output.write(b",")
output.write(json.dumps(entry(count), separators=(",", ":")).encode())
count += 1
output.write(b"]")
if defaults:
output.write(b',"defaults":')
output.write(json.dumps({f"minecraft:fixture_{i // 16}": i
for i in range(0, count, 16)},
separators=(",", ":")).encode())
output.write(b"}")
print(f"{path.name}: {path.stat().st_size} bytes, {count} states")
root = Path(sys.argv[1])
root.mkdir(parents=True, exist_ok=True)
write(root / "gameplay-facts.json", 55_700_000, gameplay)
# Leave room for the defaults object (~95 KB at this state count).
write(root / "facts.json", 10_020_000, facts, defaults=True)