How does String::from("")
& "".to_string()
differ in Rust?
Is there any difference in stack and heap allocation in both cases?
How does String::from("")
& "".to_string()
differ in Rust?
Is there any difference in stack and heap allocation in both cases?
How does
String::from("")
&"".to_string()
differ in Rust?
They're part of different protocols (traits): std::convert::From and alloc::string::ToString[0].
However, when it comes to &str
/String
they do the same thing (as does "".to_owned()
).
Is there any difference in stack and heap allocation in both cases?
As joelb's link indicates, before Rust 1.9 "".to_string()
was markedly slower than the alternatives as it went through the entire string formatting machinery. That's no longer the case.
[1] functionally s.to_string()
is equivalent to format!("{}", s)
, it's usually recommended to not implement ToString
directly, unless bypassing the formatting machinery can provide significant performance improvements (which is why str
/String
do it)