Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13518

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.

Upvotes: 11

Views: 6022

Answers (3)

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13518

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.

Upvotes: 14

kmdreko
kmdreko

Reputation: 59952

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.

Upvotes: 2

HJVT
HJVT

Reputation: 2192

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};
}

Upvotes: 1

Related Questions