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.

7 Likes

&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.

4 Likes

@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.

2 Likes

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

2 Likes

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.