Sub topic 7
Reusing Buffers Across Loop Iterations
This chapter assumes you know ownership and borrowing, how Vec and String store data on the heap, and how with_capacity works from the previous chapter. It shows how to keep one buffer alive across a loop so each iteration reuses its memory.
Why a loop allocates more than it needs to
A String or Vec owns a heap block. Its length is how much of that block is in use. Its capacity is how much the block can hold. When a value is dropped, the block goes back to the allocator.
Suppose a loop builds a new String on each pass. Each pass then asks the allocator for memory, may grow it several times, and frees it at the end. If you create the buffer once outside the loop and empty it on each pass, the block stays allocated and only the contents change.
clear() keeps capacity
clear() sets the length to zero and drops the elements. It does not release the memory. After the first few iterations the buffer has grown to the size your largest input needs, and later iterations usually need no allocation.
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut reader = stdin.lock();
let mut line = String::new();
let mut total = 0usize;
loop {
line.clear();
if reader.read_line(&mut line)? == 0 {
break;
}
total += line.trim_end().len();
}
println!("{}", total);
Ok(())
}read_line appends to the string you pass, so calling line.clear() first is required for correct results. Without it, each line would be added to the previous ones. Compare this with reader.lines(), which returns a new String for every line.
Writing into a buffer with write!
format! always creates a new String. When you only need the text temporarily, use write! to fill an existing one. The std::fmt::Write trait must be in scope.
use std::fmt::Write;
fn main() {
let mut out = String::with_capacity(64);
for i in 0..3 {
out.clear();
write!(out, "item-{}", i).unwrap();
println!("{}", out);
}
}Writing to a String cannot fail, so unwrap() is safe here. Pairing with_capacity with clear gives you one allocation for the whole loop, as long as the text stays under 64 bytes.
flowchart TDThe diagram below shows the lifecycle of a reused buffer.
Common errors
- Forgetting
clear(). Appending APIs such asread_line,push_strandread_to_stringkeep old contents. The program compiles and produces wrong output. - Holding a borrow across iterations. If you store
&linein a collection that outlives the iteration, the borrow checker rejects the nextline.clear(). If you need the data later, copy it withto_owned(). That allocation is then real and necessary. - Reusing a buffer after one huge input. The capacity stays at the largest size seen. In a long-running program, call
shrink_to_fit()or replace the buffer if one outlier would otherwise pin a lot of memory. - Expecting zero allocations. Reuse removes allocations only after the buffer has grown enough. The first iterations can still allocate.
Checking the result
Use the counting allocator from earlier in this tutorial. Run the loop once with a new String per pass and once with a reused one, then compare the allocation counts. Reuse is worth it when the loop is hot and the counts drop. In code that runs rarely, the extra mutable state is usually not worth the loss in clarity.
Exercise
A loop calls reader.read_line(&mut line) without calling line.clear(). The program compiles. What goes wrong, and does it affect allocations?
Show answer
read_line appends, so line accumulates every line read so far and your per-line results are wrong. The buffer also grows without bound, so it uses more memory and can reallocate as it grows. Adding line.clear() at the top of each iteration fixes both problems.
Exercise
You replace let s = format!("id-{}", id); inside a hot loop with write! into a buffer declared before the loop. Which two calls do you need on the buffer, and which trait must be imported?
Show answer
Call s.clear() at the start of each iteration, then write!(s, "id-{}", id). Import std::fmt::Write. Optionally create the buffer with String::with_capacity so the first iterations do not need to grow it.