Overhead of Rc vs Box?

Short Question: Besides storing a counter, what is the overhead of using Rc instead of Boz ?

Long Question: I have a situation where using Rc would be trivial, and using Box would be a bit more complex, and I’m trying to figure out what the overhead is (and whether, in general, to just always use Rc – it’s not clear to me what the benefit of Box is.)

Besides that tiny counter and easily optimizable increment/decrement, there’s no more runtime overhead on Rc over Box. But remember, we all know that shared mutability is the source of evil, and Rc is for shared ownership, so you can’t mutate content behind Rc. Um, who said about the RefCell? That’s evil, take him away.

Protip: If you have Rc/Arc, but somehow knows that we don’t share it at the moment, why can’t we mutate it? Check the get_mut()/make_mut() methods on them.

1 Like

Downside of Box is that you can not clone the Box if it holds a non-cloneable Type such as closures/functions ie: Box<Fn()>, while cloning an Rc<Fn()> is possible since cloning an Rc is just cloning the pointer.

1 Like

If your data is to be heap-allocated anyways and you want to share it without lifetime issues (and no mutation!) then do use Rc: the overhead of incrementing/decrementing a single counter is negligeable compared to the heap allocation / free from Box.

4 Likes