Right, the reason why folks (rightly) recommended against to_string()
in the past is because it went through the formatting machinery. Back then, we didn't have specialization at all, so all we had was the blanket impl on ToString
for all T: std::fmt::Display
. So even for &str
, it would need to go through the formatting machinery.
But not too long after Rust 1.0, we got specialization and this was one of the first things we used it: to "fix" the ToString
impl for str
so that it did the obvious and cheapest thing.
Sadly, specialization never got fully stabilized, but it's used in a smattering of places inside of std
to speed things like this up.
Therefore, today, to_string()
and to_owned()
and String::from
are all equivalent from a perf perspective. I mostly see folks using to_string()
(including myself), but I don't think any choice is particularly wrong.