Send String via channel or Arc<String>

I've seen people send Arc<String> via channel instead of String.
Why could it be used in that way?

If you clone a String you have to copy all of the data the string contains. That can be quite expensive under some circumstances. Wrapping it in an Arc means cloning just increments the reference count which is (usually) much cheaper.

Note also that, if the string is essentially immutable (i.e. it's created once and never changes), Arc<str> might be a better choice, since it avoids double indirection.

5 Likes

The only way to change the String contained in an Arc<String> would be to unwrap it from the Arc again (which only works if there is exactly one strong reference). Thus I guess Arc<str> is indeed the better choice in a lot of scenarios.

I didn't know about Arc<str> before, but I just learned it's very easy to create (Playground).

It's even easier.

(powered by this impl, you can see everything you can create an Arc<str> from in the left sidebar)

1 Like

Well, my example was meant to show how to create an Arc<str> from an allocated String (to serve as an alternative for Arc<String>). When only &'static str's are involved, you usually don't need the Arc.

1 Like