Last active
October 31, 2019 16:35
-
-
Save nayato/61e325ff36c90b125ab7b0a4f00d8471 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate criterion; | |
use criterion::{Criterion, ParameterizedBenchmark}; | |
use std::collections::HashMap; | |
use std::rc::{Rc, Weak}; | |
use std::cell::UnsafeCell; | |
type Sessions = Rc<UnsafeCell<HashMap<String, Data>>>; | |
fn bench_map_vs_rc(c: &mut Criterion) { | |
let mut map = HashMap::new(); | |
let mut map2 = HashMap::new(); | |
for i in 0..10000 { | |
map.insert(i.to_string(), Data { a: i, b: 0, c: 0, d: 0, b2: 0, c2: 0, d2: 0}); | |
map2.insert(i.to_string(), Rc::new(Data { a: i, b: 0, c: 0, d: 0, b2: 0, c2: 0, d2: 0})); | |
} | |
let map = Rc::new(UnsafeCell::new(map)); | |
let map2 = Rc::new(UnsafeCell::new(map2)); | |
let s = Session { id: "300".to_string(), sessions: map }; | |
let s2 = Session2 { id: "300".to_string(), sessions: map2.clone(), inner: Rc::downgrade(&get_ref(&map2).get("300").unwrap()) }; | |
c.bench( | |
"map_vs_rc", | |
ParameterizedBenchmark::new("map", |b, i| b.iter(|| try_map(&i.0)), vec![(s, s2)]) | |
.with_function("rc", |b, i| b.iter(|| try_rc(&i.1))), | |
); | |
} | |
criterion_group!(benches, bench_map_vs_rc); | |
criterion_main!(benches); | |
#[derive(Debug, Clone)] | |
struct Data { | |
a: u64, | |
b: u64, | |
c: u64, | |
d: u64, | |
b2: u64, | |
c2: u64, | |
d2: u64, | |
} | |
#[derive(Debug, Clone)] | |
struct Session { | |
id: String, | |
sessions: Sessions, | |
} | |
impl Session { | |
fn a(&self) -> u64 { | |
get_ref(&self.sessions).get(&self.id).map(|s| s.a).unwrap() | |
} | |
} | |
fn try_map(val: &Session) -> u64 { | |
val.a() + 1 | |
} | |
fn try_rc(val: &Session2) -> u64 { | |
val.a() + 1 | |
} | |
type Sessions2 = Rc<UnsafeCell<HashMap<String, Rc<Data>>>>; | |
#[derive(Debug, Clone)] | |
struct Session2 { | |
inner: Weak<Data>, | |
id: String, | |
sessions: Sessions2, | |
} | |
impl Session2 { | |
fn a(&self) -> u64 { | |
self.inner.upgrade().map(|s| s.a).unwrap() | |
} | |
} | |
pub fn get_ref<T>(cell: &Rc<UnsafeCell<T>>) -> &T { | |
unsafe { &*cell.as_ref().get() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment