Sub topic 2
Allocate Only When Needed with `Cow`
Assume you know Rust ownership, borrowing, lifetimes, Vec, String, and iterators. This chapter focuses on reducing allocations without changing program behavior. Measure before and after each change.
Clone on write with `Cow`
Cow means “clone on write.” It can hold either a borrowed value or an owned value. A function can return the input without allocating when no change is needed, then allocate only when it must create a modified result.
use std::borrow::Cow;
fn expand_tabs(input: &str) -> Cow<'_, str> {
if input.contains('\t') {
Cow::Owned(input.replace('\t', " "))
} else {
Cow::Borrowed(input)
}
}
fn main() {
println!("{}", expand_tabs("plain text"));
println!("{}", expand_tabs("one\ttab"));
}The first call returns a borrow into the original string. The second call owns a new String. Cow is useful when the unchanged path is common and the modified path is occasional.
Preallocate known capacity
A growing Vec or String may allocate several times. Each growth can copy existing data into a larger buffer. Use with_capacity when you know an approximate or exact size. Use reserve when you learn the required space later.
| Technique | Use it when |
|---|---|
| `with_capacity(n)` | You know the needed capacity before creating the collection |
| `reserve(n)` | You need additional capacity after creation |
fn grow_with_capacity(n: u32) -> Vec<u32> {
let mut values = Vec::with_capacity(n as usize);
for value in 0..n {
values.push(value);
}
values
}
fn add_more(values: &mut Vec<u32>, extra: usize) {
values.reserve(extra);
for value in 0..extra as u32 {
values.push(value);
}
}Capacity is not length. A vector can have room for more elements while its len() remains unchanged.
Reuse buffers in loops
Clear a buffer instead of creating a new one for every iteration. clear() removes the elements but keeps the allocated capacity.
use std::fmt::Write;
fn main() {
let mut output = String::with_capacity(32);
for number in 0..3 {
output.clear();
write!(&mut output, "item-{number}").unwrap();
println!("{output}");
}
}This pattern keeps the buffer’s allocation across iterations. It is especially useful for parsing input, formatting records, or building temporary output.
Exercise
When should you prefer Cow<'_, str> over always returning a new String?
Show answer
Prefer it when most calls can return the original borrowed text and only some calls need a modified owned string.