简体   繁体   English

将 `&str` 添加到 `String` 的最有效方法是什么?

[英]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.

相关问题 在 Rust 中将换行符添加到字符串(或 &amp;str)末尾的最轻松的方法是什么? - What is the most painless way to add a newline to the end of a String (or &str) in Rust? 迭代 [false, true] 的最有效方法是什么? - What is the most efficient way to iterate in [false, true]? 保持字符串引用集合的最有效方法 - Most efficient way to keep collection of string references 将字符串转换为 &amp;str 的惯用方法是什么? - What is the idiomatic way to convert a String to &str? 将元素插入已排序向量的最有效方法是什么? - What's the most efficient way to insert an element into a sorted vector? 在Rust中重用迭代器的最有效方法是什么? - What's the most efficient way to reuse an iterator in Rust? 克隆固定大小数组的最有效方法是什么? - What is the most efficient way to clone a fixed-sized array? 在不立即将整个文件加载到 memory 的情况下,分块读取大文件的最有效方法是什么? - What is the most efficient way to read a large file in chunks without loading the entire file in memory at once? 在给定数值范围的引用上使用迭代器的最有效方法是什么? - What is the most efficient way to have a iterator over the references of a given numeric range? 获取多个整数用户输入并将其存储在 Vec 中的最有效方法是什么<i32> ? - What is the most efficient way of taking a number of integer user inputs and storing it in a Vec<i32>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM