Reallocation copies existing data into a larger memory area when current storage cannot hold new data. Repeated string growth can trigger excessive allocations and copying. section 2.4.1
A growable Rust String manages reallocation through:
- Length, which counts valid elements, and capacity, which counts elements the buffer can hold. section 2.4.1
- Appending without reallocation while the new length remains within capacity. section 2.4.1
- A new allocation and data copy when mutation exceeds capacity; the growth strategy is not guaranteed. section 2.4.1
- Preallocation with String::with_capacity to reduce growth-related work when the required size is known. section 2.4.1
Listing 2.16 Creating a very large string one character at a time in Python
x = "" for _ in range(0, 10_000_000): x += "." print(len(x))
Compare repeated Python string concatenation, which creates many copied strings during a ten-million-character build. section 2.4.1
Listing 2.17 Creating a very large string one character at a time in Rust
fn main() {
let mut x = String::new(); #1
for _ in 0..10_000_000 {
x.push('.');
}
println!("{}", x.len());
}
See Rust append characters to a growable String while hiding most buffer maintenance. section 2.4.1
Listing 2.18 Preallocating strings to aid performance
fn main() {
let mut x = String::with_capacity(10_000_000); #1
for i in 0..10_000_000 {
x.push('.');
}
println!("{}", x.len());
}
See known-size preallocation avoid capacity growth during repeated appends. section 2.4.1
