[英]What is the most efficient way to prepend a `&str` to a `String`?
What is the most efficient way to prepend a &str
to a String
?将&str
添加到String
的最有效方法是什么? Right now I am allocating a new String
and pushing to it:现在我正在分配一个新的String
并推送给它:
fn push_front(s: String, prefix: &str) -> String {
let prefix = prefix.to_owned();
prefix.push_str(&s);
prefix
}
Is there a more efficient way?有没有更有效的方法? I don't see a String::push_front
function in the standard library.我在标准库中没有看到String::push_front
function 。
You can use String::insert_str
:您可以使用String::insert_str
:
s.insert_str(0, prefix);
Instead of allocating a new String
and (potentially) allocating for the push, insert_str
reserves capacity in the underlying vector and shifts the elements of s
to the right. insert_str
不是分配一个新的String
和(可能)为 push 分配,而是在底层向量中保留容量并将s
的元素向右移动。 If the String
already has sufficient capacity for prefix
, it avoids the allocation altogether.如果String
已经有足够的prefix
容量,它会完全避免分配。 This means it will only require at most one allocation, rather than two.这意味着它最多只需要一次分配,而不是两次。
Use String::insert_str
:使用String::insert_str
:
fn push_front(s: String, prefix: &str) -> String {
s.insert_str(0, prefix);
s
}
This will use 0-1 allocations instead of the 1-2 in the original.这将使用 0-1 分配而不是原始的 1-2。
There isn't a String::push_front, but there is String::insert_str.没有 String::push_front,但有 String::insert_str。
fn main(){
let a = "foo";
let mut b = "bar".to_owned();
b.insert_str(0,a);
dbg!{b};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.