Skip to content

Instantly share code, notes, and snippets.

@FlareFlo
Created October 7, 2023 22:25
Show Gist options
  • Save FlareFlo/79595900cfa4d5f68cdc66ea2b965a9f to your computer and use it in GitHub Desktop.
Save FlareFlo/79595900cfa4d5f68cdc66ea2b965a9f to your computer and use it in GitHub Desktop.
Small types copy versus referencing
/*
https://github.com/sharkdp/hyperfine
Command run:
cargo build --release
hyperfine target/release/playground #(playground is project name)
profile used:
opt-level = 3
lto = true
Results with references:
Time (mean ± σ): 1.650 s ± 0.011 s [User: 1.646 s, System: 0.001 s]
Range (min … max): 1.634 s … 1.660 s 10 runs
Results without references (copying):
Time (mean ± σ): 1.653 s ± 0.020 s [User: 1.639 s, System: 0.010 s]
Range (min … max): 1.633 s … 1.703 s 10 runs
My conclusion:
A difference of 0,181% in performance is effectively within noise thresholds.
*/
use std::time::Instant;
const N: usize = 100_000;
#[derive(Clone, Copy)]
enum Shape {
Rectangle(Rectangle),
Triangle(Triangle),
Square(Square),
}
impl Shape {
// Remove ref
fn area(&self) -> f32 {
match self {
Shape::Rectangle(r) => r.area(),
Shape::Triangle(t) => t.area(),
Shape::Square(s) => s.area(),
}
}
}
#[derive(Clone, Copy)]
struct Square {
side: f32,
}
impl Square {
#[inline(always)]
// Remove ref
fn area(&self) -> f32 {
self.side * self.side
}
}
#[derive(Clone, Copy)]
struct Rectangle {
width: f32,
height: f32,
}
impl Rectangle {
#[inline(always)]
// Remove ref
fn area(&self) -> f32 {
self.width * self.height
}
}
#[derive(Clone, Copy)]
struct Triangle {
base: f32,
height: f32,
}
impl Triangle {
#[inline(always)]
// Remove ref
fn area(&self) -> f32 {
0.5 * self.base * self.height
}
}
fn total_area(shapes: &[Shape]) -> f32 {
shapes.iter().fold(0.0, |a, s| a + s.area())
}
fn main() {
let shapes: Vec<Shape> = vec![
Shape::Rectangle(Rectangle {
width: 4.0,
height: 4.0,
}),
Shape::Triangle(Triangle {
base: 4.0,
height: 4.0,
}),
Shape::Square(Square { side: 4.0 }),
];
let shapes = shapes.repeat(N);
let mut total = 0.0;
for _ in 0..10_000 {
total += total_area(&shapes);
}
// prevent rustc from optimizing away the computation
println!("{total}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment