Why does Arc cost more than Rc, and when do you still pick Rc?
Both keep a strong and a weak count in the heap block. Rc changes them with plain adds; Arc with atomic ones, which keep core caches in agreement and cost more, worse under contention. On one thread Rc shares the value for less.
- Believing
Arclocks the value on every access, when onlycloneanddroptouch the atomic count - Using
Arceverywhere just in case and paying for atomic operations in single-threaded code - Expecting
Arcalone to allow mutation from several threads without aMutexor an atomic type
- Why does the compiler stop an
Rcfrom reaching another thread instead of checking at run time? - How can a function that only reads the shared value avoid touching the count at all?
Only clone and dropping a pointer touch the count; reading the value through an Rc or an Arc is an ordinary dereference with no atomic operation:
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
fn total(v: &[i32]) -> i32 {
v.iter().sum()
}
fn main() {
let local = Rc::new(vec![1, 2, 3]);
let view = Rc::clone(&local); // a plain +1
println!("{} {}", total(&view), Rc::strong_count(&local)); // 6 2
let shared = Arc::new(vec![1, 2, 3]);
let worker = Arc::clone(&shared); // an atomic +1
let h = thread::spawn(move || total(&worker));
println!("{}", h.join().unwrap()); // 6
println!("{}", Arc::strong_count(&shared)); // 1
}An atomic add makes the core take the cache line holding the count for its own exclusive use; when clone and drop come from several threads at once, that line bounces between cores and the price grows. Hence two rules. Inside one thread take Rc: the compiler itself keeps it out of thread::spawn (E0277), so the choice cannot go wrong. And pass a function that only reads a &T or &[T], like total above — then the count does not change at all, whether it belongs to an Rc or an Arc.