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

夙愿已清 提交于 2020-06-16 09:42:30

问题


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

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


回答1:


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.19 "".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)



来源:https://stackoverflow.com/questions/61475158/how-does-stringfrom-to-string-differ-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!