Concat
Consider a string
in Rust: we can loop over its characters, test its length, or add additional data to it. The term "concat" refers to a way to add data to a string
.
In Rust, the String
struct
contains a growable buffer. This is managed by the type itself, so we do not need to write this code ourselves. This buffer is useful when concatenating.
Concat
exampleTo start, we see 3 different ways to concatenate strings. With "to_owned
" we get a String
instance from a str
reference. This is needed to have a growable buffer.
string
to the leftmost String
. A str
reference can be added to a String
.Push_str
appends a str
reference to the end of the current String
. It is like a concat, add, or append function.fn main() { let left = "string1"; let right = "string2"; // Use add operator. let result1: String = left.to_owned() + right; println!("{result1}"); // Use new and push_str. let mut result2 = String::new(); result2.push_str(left); result2.push_str(right); println!("{result2}"); // Use from and push_str. let mut result3 = String::from(left); result3.push_str(right); println!("{result3}"); }string1string2 string1string2 string1string2
Capacity
benchmarkIn Rust the String
type is like a StringBuilder
from other languages—String
has a growable buffer. This optimizes repeated appends.
str
reference to the result String
many times.with_capacity
to avoid having to resize the underlying buffer.with_capacity
gives a small performance boost, but even without a capacity, the String
handles many appends in an efficient way.with_capacity
to optimize repeated concatenations to a String
.use std::time::*; const MAX: usize = 20000000; fn main() { // Version 1: use no capacity. let t0 = Instant::now(); let mut result1 = String::new(); for _ in 0..MAX { result1 += "abc"; } println!("{}", t0.elapsed().as_millis()); // Version 2: use with_capacity. let t1 = Instant::now(); let mut result2 = String::with_capacity(MAX * 3); for _ in 0..MAX { result2 += "abc"; } println!("{}", t1.elapsed().as_millis()); println!("{} {}", result1.len(), result2.len()); }16 ms 13 ms (with_capacity) 60000000 60000000
We can concat Strings with plus or push_str
. For repeated concats, using a capacity can improve performance, but Strings support concatenation in an optimized way.