Skip to content

Instantly share code, notes, and snippets.

@Restioson
Last active January 16, 2020 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Restioson/6e2f522836ec95f356d585b07039c7e4 to your computer and use it in GitHub Desktop.
Save Restioson/6e2f522836ec95f356d585b07039c7e4 to your computer and use it in GitHub Desktop.
//! Custom cell impl, internal use only
use std::{cell::UnsafeCell, fmt, rc::Rc};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::cell::RefCell;
pub(crate) struct Cell<T> {
inner: Rc<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Cell<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub(crate) fn get_ref(&self) -> &T {
unsafe { &*self.inner.as_ref().get() }
}
pub(crate) fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}
fn bench_get_ref(c: &mut Criterion) {
c.bench_function(
"custom cell get_ref",
|b| {
let to_clone = Cell::new(black_box(20));
b.iter_with_setup(
|| to_clone.clone(),
|cell| cell.get_ref().clone()
)
}
);
}
fn bench_get_mut(c: &mut Criterion) {
c.bench_function(
"custom cell get_mut",
|b| {
let to_clone = Cell::new(black_box(20));
b.iter_with_setup(
|| to_clone.clone(),
|mut cell| cell.get_mut().clone()
)
}
);
}
fn bench_borrow_rc_refcell(c: &mut Criterion) {
c.bench_function(
"rc refcell borrow",
|b| {
let to_clone = Rc::new(RefCell::new(black_box(20)));
b.iter_with_setup(
|| to_clone.clone(),
|cell| cell.borrow().clone()
)
}
);
}
fn bench_borrow_mut_rc_refcell(c: &mut Criterion) {
c.bench_function(
"rc refcell borrow_mut",
|b| {
let to_clone = Rc::new(RefCell::new(black_box(20)));
b.iter_with_setup(
|| to_clone.clone(),
|cell| cell.borrow_mut().clone()
)
}
);
}
criterion_group!(benches, bench_get_ref, bench_get_mut, bench_borrow_rc_refcell, bench_borrow_mut_rc_refcell);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment