by unlinked_dll · 6y ago · 0 comments
#[derive(Copy,Clone,Deserialize)]
struct Point {
x: f64,
y: f64,
z: f64
}
#[derive(Copy,Clone,Deserialize)]
struct Schema {
coordinates: Vector<Point>
}
fn main() -> Result<(), Box<dyn Error>> {
let mut json_content = String::new();
File::open("1.json")? // don't need Path
.read_to_string(&mut json_content)?;
let schema = serde_json::from_str::<Schema>(&json_content)?;
let len = schema.coordinates.length();
let (x, y, z) =
schema.coordinates
.iter()
.fold((0.0, 0.0, 0.0),
|(xsum, ysum, zsum), (x, y, z)|{
(xsym + x, ysum + y, zsum + z)
});
println!("x: {}, y: {}, z: {}", x / len, y / len, z / len);
Ok(())
}How much faster is that?
Serde is one of the fastest deserializers out there. It excels when it has a defined schema to decode, using the #[derive] syntax should offload the work of the deserializer immensely and negate the effects of looking up fields which may not exist.
As well, using rust’s iterator adaptors like fold can allow the compiler to make better optimizations for things like summing vectors of floats, such as SIMD/auto vectorizing easier. It’s also better at eliminating or reducing bounds checks.
Using iterator abstractions is much more “beautiful” in my opinion to for loops, as well in rust tends to generate better assembly than indexing into collections like slices and vectors.