Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to prepend a `&str` to a `String`?

Tags:

rust

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.

like image 621
Ibraheem Ahmed Avatar asked Jan 24 '23 12:01

Ibraheem Ahmed


2 Answers

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.

like image 183
Ibraheem Ahmed Avatar answered Mar 08 '23 15:03

Ibraheem Ahmed


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.

like image 27
kmdreko Avatar answered Mar 08 '23 14:03

kmdreko