In some programming languages, calling a function on a type instance may be slower than a top-level function. We test this issue in Rust with impl.
use std::time::*;
fn test_value(value: &str) {
if value !=
"bird" {
panic!(
"ERROR");
}
}
struct Example {
value: String,
}
impl Example {
fn test_value(&self) {
if self.value !=
"bird" {
panic!(
"ERROR");
}
}
}
fn main() {
if let Ok(max) =
"100000000".parse::<usize>() {
let value =
"bird".to_owned();
let ex = Example {
value:
"bird".to_owned(),
};
// Version 1: test with top-level function.
let t0 = Instant::now();
for _ in 0..max {
test_value(&value);
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: test with function in impl block.
let t1 = Instant::now();
for _ in 0..max {
ex.test_value();
}
println!(
"{} ms", t1.elapsed().as_millis());
}
}
34 ms test_value()
33 ms ex.text_value()