Sub topic 3
Spotting Hidden Allocations in Everyday Code
This chapter assumes you are comfortable with ownership and borrowing, with Vec, String and Box, and with iterators and closures. It also assumes you can run cargo run and cargo test. The previous chapters covered where allocations come from and how to count them. This one trains your eye to recognize them while reading code.
Why allocations hide
Rust never allocates without a call that says so somewhere in the type or the library. The call is often a short method name that reads like a cheap conversion. to_string, clone, collect and format! all look like plain data handling, and each can ask the allocator for memory.
Hidden allocations rarely come from exotic code. They come from habits:
- Making an owned value only so the compiler stops complaining.
- Building a temporary value to pass somewhere that only needed to look at it.
- Letting a collection grow one element at a time.
Spotting them means asking one question of every line: does this create a value that owns heap memory?
Check a suspicion with a counter
Reading code gives you suspects. A measurement gives you facts. This program wraps the system allocator and counts allocation calls around a closure. It reuses the counting allocator from the previous chapter and adds a helper, count.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn count<R>(f: impl FnOnce() -> R) -> (R, usize) {
let before = ALLOCS.load(Ordering::Relaxed);
let result = f();
let after = ALLOCS.load(Ordering::Relaxed);
(result, after - before)
}
fn main() {
let names = vec!["ada".to_string(), "grace".to_string(), "linus".to_string()];
let (_, new_string) = count(String::new);
let (_, to_string) = count(|| "hello".to_string());
let (_, formatted) = count(|| format!("id-{}", 7));
let (_, cloned) = count(|| names.clone());
let (_, pushed) = count(|| {
let mut v = Vec::new();
for i in 0..100u32 {
v.push(i);
}
v
});
let (_, summed) = count(|| names.iter().map(|s| s.len()).sum::<usize>());
println!("String::new {new_string}");
println!("to_string {to_string}");
println!("format! {formatted}");
println!("Vec<String> clone {cloned}");
println!("100 pushes {pushed}");
println!("iterator sum {summed}");
}On a recent stable toolchain the counts are 0, 1, 1, 4, 6 and 0. The exact numbers can change between compiler versions, so treat them as an illustration. Two details explain them:
- Cloning a
Vec<String>costs one allocation for the vector and one for each string. - The 100 pushes cost 6 allocations because the vector's capacity grows through 4, 8, 16, 32, 64 and 128. The wrapper does not override
realloc, so each growth step goes throughallocand is counted.
Print results after count returns, not inside the closure. Printing can touch the allocator and distort the number.
The usual suspects
| Expression | Allocates? | Notes |
|---|---|---|
| `String::new()`, `Vec::new()`, `HashMap::new()` | No | Empty collections hold no heap memory until the first insert. |
| `"x".to_string()`, `"x".to_owned()`, `String::from("x")`, `"x".into()` | Yes, once | All copy the bytes into a new `String`. |
| `n.to_string()` for a number | Yes, once | A new `String` for the digits. |
| `format!(...)` | Yes, at least once | It builds a new `String`, and may regrow if the size estimate is low. |
| `x.clone()` on `String`, `Vec`, `Box` | Yes | Deep copy. A `Vec<String>` clone allocates once per element too. |
| `slice.to_vec()` | Yes | Copies into a new vector. |
| `iter.collect::<Vec<_>>()` | Yes | At least once, more if the size is unknown and it regrows. |
| `s.to_lowercase()`, `s.replace(a, b)` | Yes | Always return a new `String`, even if nothing changed. |
| `a + &b` on `String` | Maybe | Reuses `a`'s buffer, but regrows if capacity runs out. |
| `parts.join(",")`, `parts.concat()` | Yes | One result buffer. |
| `Box::new(x)` | Yes, unless `x` has size zero | One heap block. |
| `Rc::new(x)`, `Arc::new(x)` | Yes | The value and its counters share one block. `Rc::clone` and `Arc::clone` do not allocate. |
| `s.chars()`, `s.lines()`, `s.split(' ')`, `s.trim()` | No | Return borrowed views or lazy iterators. |
Method names do not tell you which row you are on. to_lowercase and trim both look like text cleanup, but only one allocates.
Patterns worth recognizing
Owned values made only to be read
This is the most common case. A function takes String or &String when it only reads the text, so callers convert first:
fn is_admin(name: String) -> bool {
name == "root"
}
fn check(user: &str) -> bool {
is_admin(user.to_string()) // allocates a copy that is dropped immediately
}If the body only reads the argument, the parameter should be &str. The next chapter covers this fix in detail.
Temporary keys in lookups
Building a String just to search a map is a frequent offender:
use std::collections::HashMap;
fn hits_slow(counts: &HashMap<String, u32>, key: &str) -> u32 {
counts.get(&key.to_string()).copied().unwrap_or(0) // allocates on every call
}
fn hits_fast(counts: &HashMap<String, u32>, key: &str) -> u32 {
counts.get(key).copied().unwrap_or(0) // String: Borrow<str>, no allocation
}
fn main() {
let mut counts = HashMap::new();
counts.insert("rust".to_string(), 3);
println!("{} {}", hits_slow(&counts, "rust"), hits_fast(&counts, "rust"));
}HashMap::get accepts any type that the key type can be borrowed as. A String key can be searched with a &str. The same applies to contains_key, remove, and BTreeMap.
Eager arguments
Arguments are evaluated before the call, whether or not the callee uses them. unwrap_or, ok_or and map_or take a ready-made value. If building it allocates, you pay every time:
fn display_name(found: Option<String>, id: u32) -> String {
// allocates a String even when `found` is Some:
// found.unwrap_or(format!("user-{id}"))
found.unwrap_or_else(|| format!("user-{id}")) // allocates only on None
}
fn main() {
println!("{}", display_name(Some("ada".to_string()), 1));
println!("{}", display_name(None, 2));
}The _else variants take a closure, so the work runs only when needed.
Clones that satisfy the borrow checker
A .clone() added to silence an error is easy to miss in review. Look for clones of whole structs or vectors inside loops, and for .clone() on a value that is dropped a few lines later. Cloning Rc or Arc is cheap and does not allocate. Cloning the data inside them is not.
Collect, then iterate
let v: Vec<_> = it.collect(); followed by one loop or one .iter() chain allocates a vector whose only job is to be read once. It is hidden by how natural it looks. A later chapter covers replacing it with a lazy chain.
Growth one element at a time
An empty Vec or String that is filled in a loop reallocates repeatedly, as the counter showed. Each step may also copy the existing contents. When you know or can estimate the final size, tell the collection so. Preallocation gets its own chapter.
Boxes behind abstractions
Some allocations come from types instead of calls:
Box<dyn Error>and.into()from a string literal allocate when the error is created.Box<dyn Fn(...)>allocates the closure's captured state.Vec<Box<dyn Trait>>allocates once per element.- A boxed async future allocates every time it is created, as with
Pin<Box<dyn Future>>.
These costs are paid at creation, so they matter most on hot paths and much less on a once-per-process setup path.
Reading signatures for clues
Signatures often tell you before you run anything:
- A function that takes
StringorVec<T>by value either stores it or forces callers to allocate one. - A function that returns
StringorVec<T>allocates at least once per call. Comparetrim, which returns&str, withto_lowercase, which returnsString. - A function that returns
Cow<'_, str>, such asString::from_utf8_lossy, allocates only in some cases. - A
-> impl Iteratorreturn is usually a sign that no collection is built.
Triage before you rewrite
Exercises
Exercise
In fn tag(id: u32) -> String, the body is format!("item-{}", id). A caller runs let t = tag(5); println!("{}", t); inside a loop of a million iterations. How many allocations should you expect per iteration from this code, and where would you look to remove them?
Show answer
At least one per iteration, from the format! inside tag, which builds a new String on every call. To remove it, change the design so the caller supplies a reusable String and the function writes into it, for example with write! after clear(), or print directly with println!("item-{}", id) and skip the String. Confirm with the count helper before and after.
Exercise
Which line allocates on every call even when the map contains the key, and what is the fix?
let n = map.get(&word.to_lowercase()).copied().unwrap_or(0); where map: HashMap<String, u32> and word: &str.
Show answer
The call word.to_lowercase() always allocates a new String, and & on it is only a borrow of that temporary. The fix depends on the data. If the map keys are already lowercase and the input is usually lowercase, check first and only lowercase when needed (a later chapter shows Cow for this). If you control the map, store lowercase keys and normalize the input once, outside the hot loop. Passing word directly would be wrong if the stored keys are lowercase and the input is not.