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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With