New/Drop cost of Rc<T> vs Ref<T> (from RefCell)

  1. I understand that Rc<T> and Ref (from RefCell) are generally used for different purposes.

  2. However, I have a situation where a function call only needs to temporarily refer to some value. My choices are:

  • return a Rc<T>
  • return a Ref<T> from a RefCell
  • return a &T // this isn't possible in current design afaik
  • return a T // T might be large and expensive to copy

Thus, question: what is the New/Drop cost of Rc vs Ref? Both seems to have to (1) increment counter on new, and (2) dec counter on Drop. Are their costs basically equal?

There is a difference, Ref<T> only allows temporary access to the value, while giving Rc<T> will allow the caller to use the value as long as they want by just keeping the Rc<T> alive. Which do you want?

1 Like
  1. I only need temporary access.

  2. The XY problem is that I'm building a Functional-Reactive-Programming like system where we have a Directed Acyclic Graph. Each node has a typed RefCell in it storing the current value. Each node has up to 4 parents. When we update a node, we have to grab Ref<T0>, Ref<T1>, Ref<T2>, Ref<T3> from the parents to compute the node's new value.

  3. Thus, only having temporary access is fine. (the computation returns a new value, not referring to parents).

  4. My main concern is whether a Ref or a Rc is cheaper, as this gets used on every node of the graph, and the graph is re evaluated at up to 60fps.

If you can use Ref use Ref. Rc is only required, if you have to deal with (true) multiple ownership, i.e. the data has a lifetime 'a or 'b, but neither 'a: 'b nor 'b: 'a is appropriate.

3 Likes

Both should amount to the same new/drop cost: increment/decrement a non-atomic integer, and a comparison to zero or something.

1 Like

It is my understanding that Rc::new involves heap allocation, while Ref doesn't. However, like others answered, the important part is to express what you mean in your API: multiple ownership is Rc, just a reference (in presence of potential inner mutability) is Ref.

1 Like

Well, Rc::new involves heap allocation, but Rc::clone doesn't.

1 Like

I'm not sure I understand your point, as OP asked about Rc::new? Unless them having a Ref almost guarantees there's an Rc somewhere already?

1 Like

Regarding performance, I assumed was comparing a Rc::clone to a Ref returned from a RefCell, in both cases assuming a Rc or RefCell already exists.

1 Like
  1. Sorry for the confusion. I stated "Rc constructor/drop vs Ref constructor/drop", however I meant to ask "Rc clone/drop vs Ref constructor/drop"

  2. Sounds like the two are approximately the same cost. I'll stick with Ref.

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.