Sub topic 7
Reusing buffers across loop iterations
This chapter assumes you know ownership and borrowing, can use String and Vec, and have read the earlier chapters on stack and heap storage and on measuring allocations. It covers one technique: keeping a single buffer alive across loop iterations so the loop stops allocating once the buffer has grown to its working size.
Why a loop allocates more than you expect
A String or Vec owns a heap block. When you create one inside a loop body, the allocator is called on the first write and the block is freed when the value drops at the end of the iteration. A loop that runs a million times can make a million allocation and free pairs, even when every line is short.
These forms all create a fresh buffer each time through a loop:
let mut line = String::new();inside the loop, followed by a read into it.format!(...)used only to produce text that is printed or appended elsewhere.let mut parts = Vec::new();inside the loop, filled and then discarded..to_string()or.collect::<Vec<_>>()on a per-item basis.
The fix is to move the buffer outside the loop and empty it at the start of each iteration. Emptying a buffer does not release its memory. clear() sets the length to zero and keeps the capacity, so the next iteration writes into memory that is already there.
Reusing a String with clear
The standard example is reading lines. BufRead::read_line appends to the String you pass in, so the buffer must be cleared between calls.
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(())
}The String allocates while it grows to fit the longest line seen so far. After that, later lines that are no longer than that fit in the existing capacity, and the loop makes no further allocations. The lines() iterator, by comparison, returns a new String for every line.
Formatting into an existing buffer
format! always returns a new String. If you only need the text for a moment, write into a buffer you already own with write!. The macro needs the std::fmt::Write trait 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 the unwrap is safe here. The Result exists because the fmt::Write trait is also used with writers that can fail.
The same idea works for functions. Instead of returning a String, let the caller supply the destination.
use std::fmt::Write;
fn render_row(out: &mut String, id: u32, name: &str) {
write!(out, "{id:>4} | {name}").unwrap();
}
fn main() {
let rows = [(1, "alpha"), (22, "beta"), (333, "gamma")];
let mut buf = String::new();
for (id, name) in rows {
buf.clear();
render_row(&mut buf, id, name);
println!("{}", buf);
}
}Standard library APIs follow this pattern: read_line, read_to_string and read_to_end all take &mut buffers. Your own helper functions can do the same. A common convention is to append to the buffer and let the caller decide when to clear it.
The lifecycle of a reused buffer
The diagram shows what happens to the buffer's length and capacity across iterations.
Reallocation happens only on the "no" branch. After a few iterations the buffer reaches the size of the largest input, and the "no" branch stops being taken. You can also skip the warm-up by calling String::with_capacity or Vec::with_capacity with a good estimate, as covered in the previous chapter.
Reusing a Vec
Vec works the same way. clear() drops the elements and keeps the allocation. For element types without a destructor, such as integers, dropping is free.
The next program splits each line on commas and prints the fields. It reuses both the String for the line and the Vec for the field positions.
use std::io::BufRead;
fn main() {
let input = "a,bb,ccc\ndddd,e\n";
let mut reader = input.as_bytes();
let mut line = String::new();
let mut spans: Vec<(usize, usize)> = Vec::new();
loop {
line.clear();
if reader.read_line(&mut line).unwrap() == 0 {
break;
}
let text = line.trim_end();
spans.clear();
let mut start = 0;
for (i, _) in text.match_indices(',') {
spans.push((start, i));
start = i + 1;
}
spans.push((start, text.len()));
for &(s, e) in &spans {
print!("[{}]", &text[s..e]);
}
println!();
}
}The output is:
[a][bb][ccc]
[dddd][e]The Vec stores byte ranges rather than &str slices. That is deliberate, and the next section explains why.
The borrow checker and reused buffers
Suppose you declared let mut fields: Vec<&str> = Vec::new(); before the loop and pushed slices of line into it. The compiler rejects this. The type Vec<&'a str> has one lifetime 'a for the whole loop, so the slices would have to stay valid across iterations. But line.clear() and read_line need &mut line at the start of each iteration, and that conflicts with the outstanding borrows. This is a correct rejection: after clear(), the old slices would point at bytes that are about to be overwritten.
You have three ways out:
- Store indexes or ranges, as in the example above, and slice at the point of use.
- Declare the
Vec<&str>inside the loop body. This is simple, but it allocates once per iteration again. - Process each field as it is found, using the iterator directly, so no collection is needed. The chapter on iterator chains covers this.
Prefer option 3 when you can, and option 1 when you need to revisit the fields.
Handing off ownership without losing the buffer
Sometimes each iteration must pass the data to another owner, such as sending a batch down a channel. Moving the Vec out leaves you with nothing to reuse. These patterns keep allocations down:
drain(..)yields the elements by value and keeps theVec's capacity.std::mem::take(&mut batch)moves the buffer out and leaves an emptyVecwith zero capacity. You then allocate again on the next push.std::mem::replace(&mut batch, Vec::with_capacity(n))hands off the full buffer and gives you a fresh one with the capacity you chose. This costs one allocation per batch rather than one per element, which is usually enough.
fn main() {
let mut batch: Vec<String> = Vec::with_capacity(4);
let mut sent: Vec<Vec<String>> = Vec::new();
for i in 0..10 {
batch.push(format!("msg-{i}"));
if batch.len() == 4 {
let full = std::mem::replace(&mut batch, Vec::with_capacity(4));
sent.push(full);
}
}
// Flush the remainder, keeping the buffer's capacity for reuse.
let rest: Vec<String> = batch.drain(..).collect();
sent.push(rest);
for b in &sent {
println!("{:?}", b);
}
}The final collect allocates a new Vec, so this example reuses batch but not the flushed remainder. Only a consumer that accepts &mut Vec or an iterator can avoid that last copy.
Pitfalls
Capacity never shrinks on its own
A buffer keeps the capacity of its largest use. If one line in a log is 200 MB, the String holds 200 MB until it is dropped, even if every other line is 80 bytes. Long-running services should cap this.
fn trim_buffer(line: &mut String) {
const MAX_KEEP: usize = 64 * 1024;
if line.capacity() > MAX_KEEP {
line.clear();
line.shrink_to(4096);
}
}
fn main() {
let mut line = String::with_capacity(1 << 20);
line.push_str("short");
trim_buffer(&mut line);
println!("capacity now at most {}", line.capacity().max(4096));
}shrink_to(n) lowers the capacity to at least n. It may keep more, so treat the result as a request, not a guarantee.
Stale data after a partial overwrite
If you reuse a Vec<u8> through an API that writes into the slice, such as Read::read, the buffer's old contents remain past the number of bytes returned. Use only &buf[..n]. With read_to_end, which appends, clear first.
Sharing buffers across threads
One buffer per thread is the simple rule. Putting a buffer behind a Mutex so all threads share it turns the allocation cost into lock contention, which is often worse. Give each worker its own buffer, created before its loop starts.
Reuse can hurt readability
A buffer shared across many steps of a long loop makes it hard to see which step last wrote to it. Keep reuse local to a tight loop, give the buffer a clear name such as scratch or line, and document that its contents are valid only within one iteration.
Which reuse tool fits
| Situation | Reuse tool | Allocation behavior |
|---|---|---|
| Reading lines from a reader | One `String` plus `clear()` and `read_line` | Allocates only when a line exceeds capacity |
| Building short text per item | `write!` into a reused `String` | No allocation after warm-up |
| Collecting temporary results | One `Vec` plus `clear()` | Allocates only when growing |
| Emptying a buffer and processing its items | `drain(..)` | Keeps capacity |
| Passing a full buffer to another owner | `mem::replace` with a presized `Vec` | One allocation per batch |
| Rare huge inputs in a long-running process | `shrink_to` after use | Returns memory, may allocate again later |
Check it with a measurement
Reuse is only worth the extra code when the loop is hot. Use the counting allocator from the measuring chapter to compare the two versions. Wrap each version of the loop between two reads of the counter. If the count drops from roughly one per iteration to a handful in total, the change worked. If the count is already small, or the loop runs a few times, leave the simpler code alone.
Exercise
A loop calls reader.read_line(&mut line) on a buffer declared outside the loop but never calls line.clear(). What goes wrong, and which two properties does clear() have that make it the right fix?
Show answer
read_line appends, so each iteration's line is added to everything read before and the contents grow without bound. clear() sets the length to zero, which discards the old text, and it keeps the capacity, so the buffer's memory is reused rather than reallocated.
Exercise
You write let mut fields: Vec<&str> = Vec::new(); before a loop, then push slices of the reused line into it inside the loop. The compiler refuses. Explain why, and give one way to keep reusing the Vec.
Show answer
The Vec<&str> has a single lifetime covering the whole loop, so its slices would have to outlive the &mut line borrow taken by clear() and read_line on the next iteration. The old slices would point at overwritten data. One fix is to store byte ranges (usize, usize) in a reused Vec, then slice line where you use them. Another is to avoid collecting by processing each field directly from the iterator.
Exercise
A service reuses one String for every request body. After one 500 MB request, memory use stays high. What is the cause, and what call addresses it?
Show answer
Capacity never shrinks on its own, so the String keeps the 500 MB block after clear(). Call shrink_to with a smaller target (for example after clearing, when the capacity exceeds a threshold) or drop the buffer and create a new one.