Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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

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

like image 778
Asnim P Ansari Avatar asked Mar 26 '26 19:03

Asnim P Ansari


1 Answers

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)

like image 62
Masklinn Avatar answered Mar 29 '26 10:03

Masklinn