Sub topic 1
Where Allocations Come From: Stack, Heap, and the Allocator
Prerequisites
Assume you understand Rust ownership, borrowing, lifetimes, Vec, String, Box, and basic iterators. You should also be able to run Cargo programs and benchmarks.
Where allocations come from: stack, heap and the allocator
The stack stores local values with a known size and lifetime. It is fast and released automatically when a function returns. Integers, references, and most fixed-size structs usually live on the stack.
The heap stores data whose size can change or whose lifetime must outlive the current stack frame. A String stores its characters on the heap. A Vec<T> stores its elements on the heap. Box<T> stores its T on the heap while the box itself is a small stack value.
An allocation asks the global allocator for a heap region. Growing a Vec can allocate a new, larger region and move its elements. Dropping the owner eventually returns the region.
Measure first: counting allocations and profiling
A counting global allocator can show how many allocation calls a code section makes:
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 main() {
let before = ALLOCS.load(Ordering::Relaxed);
let values: Vec<u32> = (0..1000).collect();
let after = ALLOCS.load(Ordering::Relaxed);
println!("len = {}, allocations = {}", values.len(), after - before);
}This counts calls, not bytes or time. Use a profiler when you need call sites, allocation sizes, or latency.
Spotting hidden allocations in everyday code
Common allocation sources include clone, to_string, format!, String::from, and collect::<Vec<_>>(). A growing vector may reallocate several times. An iterator chain often avoids an intermediate collection:
fn count_long_words(text: &str) -> usize {
text.split_whitespace().filter(|word| word.len() > 5).count()
}Borrow instead of clone: `&str`, `&[T]` and references in APIs
Take borrowed input when a function only reads it:
fn total(values: &[u32]) -> u32 {
values.iter().sum()
}The caller keeps ownership, and the function allocates nothing. Prefer &str over String for read-only text and &[T] over Vec<T> for read-only sequences. Return owned data only when the function creates or must retain that data.
Exercise
Which parameter avoids taking ownership when a function only reads text: String or &str?
Show answer
&str; it borrows the text and does not allocate.