3

How does String::from("") & "".to_string() differ in Rust?

Is there any difference in stack and heap allocation in both cases?

Asnim P Ansari
  • 1,467
  • 12
  • 28
  • 2
    Does this answer your question? [How to create a String directly?](https://stackoverflow.com/questions/31331356/how-to-create-a-string-directly) – joel Apr 28 '20 at 08:07

1 Answers1

6

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.


[0] `ToString` is also automatically implemented if the structure implements `Display`[1]

[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)

Masklinn
  • 23,560
  • 2
  • 21
  • 39