Sub topic 13
Capacity and Avoiding Extra Allocations
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how String differs from &str. You should also have seen push, push_str, and format!. Here you will learn how a String manages its memory, when it allocates, and how to avoid allocations you do not need.
How a String stores its data
A String is a small value on the stack that points to a buffer on the heap. It holds three fields:
- A pointer to the start of the buffer.
- A length, which is the number of bytes currently in use.
- A capacity, which is the number of bytes the buffer can hold before it must grow.
The length never exceeds the capacity. The bytes between the two are reserved but unused.
Allocating heap memory costs more than ordinary work. Growing a buffer often means asking the allocator for a bigger block, copying the old bytes, and freeing the old block. Capacity lets a String do this rarely instead of on every append.
Observing length and capacity
The methods len and capacity report both values. Both count bytes, not characters.
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());
}String::new() does not allocate, so the first line prints len=0 cap=0. The exact capacity after push_str is not specified by the language. The standard library currently grows a buffer geometrically, with a minimum for small element sizes, so the second line shows a capacity of at least 5. Do not hard-code a specific number in your programs or tests. Only the guarantee capacity() >= len() is stable.
Growth is amortized
When an append would exceed the capacity, String grows its buffer by at least double. That strategy makes appends cheap on average. If you push one byte at a time, most pushes only write into spare room. Only occasionally does one trigger a reallocation.
You can watch reallocations happen by recording each time the capacity changes:
fn main() {
let mut s = String::new();
let mut last = s.capacity();
let mut reallocations = 0;
for _ in 0..1000 {
s.push('x');
if s.capacity() != last {
last = s.capacity();
reallocations += 1;
}
}
println!("final len={} cap={}", s.len(), s.capacity());
println!("capacity changed {reallocations} times for 1000 pushes");
}The count will be small, around a handful, not 1000. The exact number depends on the standard library version.
Reserving space up front
If you know roughly how much text you will build, tell the String in advance. There are two ways.
String::with_capacity(n)creates an empty string with room for at leastnbytes.reserve(additional)makes sure there is room foradditionalmore bytes beyond the current length.
fn main() {
let words = ["alpha", "beta", "gamma", "delta"];
let total: usize = words.iter().map(|w| w.len()).sum::<usize>() + words.len() - 1;
let mut joined = String::with_capacity(total);
for (i, w) in words.iter().enumerate() {
if i > 0 {
joined.push(',');
}
joined.push_str(w);
}
println!("{joined}");
println!("len={} cap>=len: {}", joined.len(), joined.capacity() >= joined.len());
}The code computes the exact byte count first: the sum of the word lengths plus one comma between each pair. The loop then never reallocates, because the buffer is already large enough.
reserve and reserve_exact
reserve may allocate more than you asked for, so later appends stay cheap. reserve_exact asks for exactly the room you request, though the allocator may still hand back a larger block. Use reserve_exact only when you are sure no more data will arrive. Otherwise, a later append may force another reallocation, which costs more than the slack you saved.
fn main() {
let mut s = String::from("abc");
s.reserve(100);
println!("after reserve: cap>=103 is {}", s.capacity() >= 103);
s.reserve_exact(10);
println!("still enough room: {}", s.capacity() >= s.len() + 10);
}The second call changes nothing here. The buffer already has room for 10 more bytes, so no allocation happens.
Giving memory back
After building a large string you may keep a lot of unused capacity. Two methods release it.
shrink_to_fit()asks the allocator to reduce capacity as close to the length as it can.shrink_to(min)reduces capacity but keeps at leastminbytes.
fn main() {
let mut s = String::with_capacity(1024);
s.push_str("short");
println!("before: len={} cap={}", s.len(), s.capacity());
s.shrink_to_fit();
println!("after: len={} cap={}", s.len(), s.capacity());
}Both methods are requests, not promises, so the capacity after shrinking may still be larger than the length. Shrinking can itself reallocate and copy. Call it once, when a string is finished growing and will live for a long time, such as one stored in a cache or a struct field. Calling it in a loop defeats its purpose.
The clear method works differently. It sets the length to zero but keeps the buffer, so the capacity is unchanged. That behavior is useful for reuse, as the next section shows.
fn main() {
let mut s = String::from("some text");
let cap = s.capacity();
s.clear();
println!("len={} capacity unchanged: {}", s.len(), s.capacity() == cap);
}Reusing a buffer in a loop
A common source of extra allocations is creating a new String on every iteration. If each iteration builds a temporary string, you can keep one buffer outside the loop and clear it each time. After the first few iterations, the buffer is large enough and no further allocations occur.
use std::fmt::Write;
fn main() {
let items = [("apple", 3), ("pear", 12), ("fig", 7)];
let mut line = String::new();
for (name, qty) in items {
line.clear();
write!(line, "{name}: {qty}").unwrap();
println!("{line}");
}
}The write! macro here comes from the std::fmt::Write trait, which String implements. It formats directly into the existing buffer. Writing to a String cannot fail, so unwrap is safe in this case. Compare this with let line = format!(...) inside the loop, which allocates a new String on every pass.
Allocation costs of common operations
Different ways of building text allocate differently. The table lists what to expect.
| Operation | Allocation behavior |
|---|---|
| `String::new()` | None until the first append. |
| `String::from("lit")` or `"lit".to_string()` | One allocation sized to the text. |
| `s.push` and `s.push_str` | None if capacity suffices, otherwise a reallocation. |
| `a + &b` | Reuses the buffer of `a`, and may reallocate if `a` lacks room. |
| `format!(...)` | Allocates a new `String`. The macro estimates a starting size, but may still grow. |
| `s.clone()` | Allocates a new buffer and copies the bytes. |
| `s.clear()` | None. Capacity is kept. |
| `s.to_uppercase()` | Always allocates a new `String`. |
The + operator deserves attention. It takes the left String by value, so it can append to that string's existing buffer. A chain like a + "-" + &b + "-" + &c can therefore run without allocating a fresh string at each step, though it may still reallocate if the buffer is too small. If a was created with enough capacity, the whole chain avoids reallocations.
Avoiding allocations in function design
Many allocations come from API design, not from the code inside a function. Three habits help.
- Accept
&strfor read-only input. A caller holding a literal or a&Stringcan then pass it without creating an owned copy. - Accept
impl AsRef<str>or&strinstead ofStringunless the function needs to keep the text. TakingStringforces callers to clone if they still need the original. - Take
&mut Stringas an output parameter when a function is called repeatedly, so the caller controls the buffer.
fn append_greeting(out: &mut String, name: &str) {
out.push_str("Hello, ");
out.push_str(name);
out.push('!');
}
fn main() {
let mut buf = String::with_capacity(64);
for name in ["Ana", "Bo", "Cy"] {
buf.clear();
append_greeting(&mut buf, name);
println!("{buf}");
}
}This pattern is common in the standard library too. For example, read_line takes a &mut String and appends to it, which lets you reuse one buffer for every line of input.
When a function sometimes needs to change its input and sometimes does not, Cow<str> is the tool. It returns a borrowed slice when no edit is needed and allocates only when it must. The Cow chapter covers it in detail.
Common mistakes
- Treating capacity as characters. Capacity and length are measured in bytes, so a string of five two-byte characters has length 10.
- Asserting exact capacity values. These are implementation details and can change between compiler releases.
- Calling
shrink_to_fitrepeatedly, which trades one cheap append for a reallocation each time. - Reserving too little. If you reserve 10 bytes and then append 1000, you still pay for growth.
- Using
with_capacityand expecting a nonzero length. The string is still empty, andlenis 0. - Optimizing without measuring. For short strings in code that is not hot, an extra allocation rarely matters. Measure first, and then reach for capacity tuning.
Summary of decisions
Use String::with_capacity when you can estimate the final size. Use clear and reuse a buffer when you build many short strings in a loop. Use shrink_to_fit once, for long-lived strings that finished growing. Prefer &str parameters, and use &mut String when a caller should own the buffer. Skip all of this when the string is small and the code is not on a hot path.
Exercise
A function builds a 40-byte log line inside a loop that runs a million times, using let line = format!("{id}: {msg}"); on each pass. Describe how to cut the allocations to roughly one, and name the trait you need to import.
Show answer
Create one String before the loop, optionally with String::with_capacity(64). On each pass call line.clear() and then write!(line, "{id}: {msg}").unwrap(). clear keeps the capacity, so after the buffer has grown to fit the longest line, no further allocations occur. You must import std::fmt::Write to use write! on a String.
Exercise
Given let mut s = String::from("héllo");, what are s.len() and the minimum value of s.capacity()? After s.clear(), what are len and capacity?
Show answer
The string héllo has 6 bytes because é takes two bytes in UTF-8, so len is 6 and capacity is at least 6. After clear, len is 0 and capacity is unchanged, because clear keeps the buffer.
Exercise
Why is reserve_exact often a worse choice than reserve when you will keep appending?
Show answer
reserve_exact allocates only the room you ask for, so the next append past that limit forces another reallocation and copy. reserve may allocate extra room, which keeps later appends from reallocating as often.