Sunday, February 7, 2016

rust: to_string() vs to_owned() for string literals

Always use to_owned() to convert a string literal.

I found this lovely explanation of to_string() vs to_owned() for rust. Only use to_string() for other types that can convert to string.

You should always be using to_owned(). to_string() is the generic conversion to a String from any type implementing the ToString trait. It uses the formatting functions and therefor might end up doing multiple allocations and running much more code than a simple to_owned() which just allocates a buffer and copies the literal into the buffer.
-- https://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441

With the caveat that this may be fixed in the future to optimize to_string() on String literals.

This may be fixed in the future with specialization, as str could implement ToString directly instead of having it go through the generic impl ToString for T where T: Display {} implementation, which employs the formatting framework. But currently I do concur with your recommendation.
-- DroidLogician

No comments: