Which is faster?

Which is faster? (Or, maybe, more correctly)
Return &String or &str from getter-method of struct, which own String

&str is 99.999% of the time what you want to be returning. &String is less useful and slightly slower (because it internally involves two pointers, instead of just one). Any function that wants a string will either require a String (because it needs ownership), so the &String isn't useful for those, or a &str (because it only needs to see the contents), so a &String isn't useful for that either.


&String is a useless type (same with &Vec and &PathBuf). It requires the string to be growable, but the immutable borrow forbids growing it. It requires it to be heap allocated, but the immutable borrow prevents taking or reusing the allocation. And it requires a double indirection to get to the data.


@kornel Is most of what you are saying true because the methods that are useful using a borrow are implemented on &str and not &Vec?

1 Like

The only thing you can do on &String which is not possible on &str is the .capacity() to calculate length of the allocated-but-unused storage. But you can't exploit the storage without &mut String.

Unlike &String, you can get &str from the string literal, Arc<str>, stack-allocated buffer, and the substring of all of them without extra allocation.


Do keep in mind though, that &mut String is useful. It can be used for what in C would be called an "out parameter".