String::from("")
& "".to_string()
在 Rust 中有何不同?
两种情况下的栈和堆分配有什么不同吗?
最佳答案
How does
String::from("")
&"".to_string()
differ in Rust?
它们是不同协议(protocol)(特征)的一部分:std::convert::From和 alloc::string::ToString [0].
但是,当涉及到 &str
/String
时,它们会做同样的事情(就像 "".to_owned()
一样)。
Is there any difference in stack and heap allocation in both cases?
正如 joelb 的链接所表明的,在 Rust 1.9 之前,"".to_string()
在遍历整个字符串格式化机制时明显比替代方案慢。现在已经不是这样了。
[0] `ToString` 如果结构实现了`Display`,也会自动实现[1]
[1] 功能上 s.to_string()
等价于 format!("{}", s)
,一般建议不直接实现 ToString
,除非绕过格式化机制可以提供显着的性能改进(这就是 str
/String
这样做的原因)
关于rust - String::from ("") & "".to_string() 在 Rust 中有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475158/