Sub topic 13
Capacity and avoiding extra allocations
This chapter assumes you know ownership and borrowing, can read Option and Result, and have used String with push and push_str. It covers how a String manages its memory and how to avoid reallocating it when you build text.
Length versus capacity
A String is a growable buffer on the heap. It tracks two numbers:
len()is how many bytes of text it holds.capacity()is how many bytes it can hold before it must get a bigger buffer.
When len would exceed capacity, the String allocates a larger buffer, copies the bytes over, and frees the old one. Growth is amortized: the capacity grows geometrically, so the cost per push stays small. The exact growth factor is an implementation detail, so never depend on specific numbers.
fn main() {
let mut s = String::new();
println!("len={} cap={}", s.len(), s.capacity());
s.push_str("hello");
println!("len={} cap={}", s.len(), s.capacity());
}A new empty String has capacity 0 and does not allocate. After the push, the capacity is at least 5.
Reserving space up front
If you know roughly how much text you will build, ask for that space once. String::with_capacity creates an empty string with a buffer ready, and reserve grows an existing one.
fn main() {
let words = ["alpha", "beta", "gamma", "delta"];
let total: usize = words.iter().map(|w| w.len()).sum::<usize>() + words.len() - 1;
let mut s = String::with_capacity(total);
for (i, w) in words.iter().enumerate() {
if i > 0 {
s.push(' ');
}
s.push_str(w);
}
println!("{s}");
println!("len={} cap={}", s.len(), s.capacity());
assert!(s.capacity() >= total);
}The capacity is a request for a minimum. Creating the string with with_capacity(total) means the loop never reallocates. The capacity is counted in bytes, not characters, so for non-ASCII text use byte lengths as above.
Reusing a buffer
clear sets the length to 0 but keeps the buffer. Reusing one String in a loop avoids a fresh allocation per iteration.
use std::fmt::Write;
fn main() {
let mut line = String::new();
for n in 1..=3 {
line.clear();
write!(line, "item-{n}").unwrap();
println!("{line} (cap={})", line.capacity());
}
}write! on a String appends formatted text directly into the existing buffer. It needs std::fmt::Write in scope. Calling format! in the loop instead would allocate a new String every time.
Giving memory back
shrink_to_fit asks the string to reduce its capacity toward its length. Use it when a long-lived string was built large and will not grow again. It may reallocate, so do not call it in a hot loop.
Common mistakes
- Chaining
a + &b + &cin a loop. Each+reuses the left string, but the buffer may still grow repeatedly. Reserve first, or usepush_str. - Calling
format!just to append.s.push_str(&format!(...))allocates a temporary. Usewrite!(s, ...). - Assuming
capacity()equals the number you passed. It can be larger. - Optimizing too early. Reserve space where you build large strings or run tight loops. For small, one-off strings the default growth is fine.
Exercise
A loop builds a log line for each of a million records using let line = format!("id={id}"); and then prints it. Name one change that reduces allocations, and say why it works.
Show answer
Create one String before the loop, call line.clear() at the start of each iteration, and use write!(line, "id={id}") (with std::fmt::Write imported). clear keeps the buffer, so after the first few iterations the string has enough capacity and no further allocation is needed. format! allocates a new String on every call.
Exercise
After let mut s = String::with_capacity(32);, what do s.len() and s.capacity() return?
Show answer
s.len() is 0 because no text has been added. s.capacity() is at least 32, because the buffer was requested with room for 32 bytes.