Is there any measurable slowdown caused by using RefCell over using a mutable reference to the containing struct? This benchmark aims to find out.
use std::cell::*;
use std::time::*;
struct Test1 {
count: RefCell<usize>,
}
struct Test2 {
count: usize,
}
fn main() {
let mut temp1 = vec![];
for _ in 0..1000 {
temp1.push(Test1 {
count: RefCell::new(0),
});
}
let mut temp2 = vec![];
for _ in 0..1000 {
temp2.push(Test2 { count: 0 });
}
if let Ok(max) =
"100000000".parse::<usize>() {
// Version 1: use RefCell.
let t0 = Instant::now();
for i in 0..max {
let mut c = temp1[i % 1000].count.borrow_mut();
*c += 1;
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: use mutable reference of struct.
let t1 = Instant::now();
for i in 0..max {
let c = &mut temp2[i % 1000].count;
*c += 1;
}
println!(
"{} ms", t1.elapsed().as_millis());
}
}
95 ms RefCell borrow_mut()
73 ms &mut