Futures, Shared and Cloning of the underlying type

Hi again :-),

I am starting to use Shared ( FutureExt in futures::future - Rust (docs.rs)) more and more and wonder about the performance of it.

Looking at the implementation of shared ( shared.rs - source (docs.rs), line 268 in particular. It uses Arc::try_unwrap() and I therefor conclude that:

If I have created a Shared<..> future and cloned it several times every task accessing once of the clones will create a clone of the underlying value (possibly expensive)? Is this understanding correct?

If so, what is the recommended way to avoid it? Do Shared<BoxFuture<'static, Arc>> instead of Shared<BoxFuture<'static, T>> to make the clone cheap?

I was sort of expecting the shared future to have a way to get a temporary reference to the resolved value, like Arc::deref but cannot seem to find anything similar for the shared future?

Regards

Viktor

1 Like

The normal way to use a Future is to poll it to completion, drop it, and only then use its result. So, Shared can't implicitly let you borrow the value from itself because it will be dropped by the time the value is available to you.

You could write a version which does what you propose (which would require polling it via an explicit &mut reference), and it would be a bit more efficient by using one heap allocation instead of two, but returning Arc is a perfectly good high-level solution for most purposes.

Thanks for confirming

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.