简体   繁体   中英

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 ? Right now I am allocating a new String and pushing to it:

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.

You can use 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. If the String already has sufficient capacity for prefix , it avoids the allocation altogether. This means it will only require at most one allocation, rather than two.

Use 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.

There isn't a String::push_front, but there is String::insert_str.

fn main(){
    let a = "foo";
    let mut b = "bar".to_owned();
    b.insert_str(0,a);
    dbg!{b};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM