Sub topic 3
Spotting hidden allocations in everyday code
This chapter assumes you can read ownership and borrowing in Rust. It also assumes you know what Vec, String and Box are, and that you have read the previous chapter on counting allocations.
Why allocations hide
Rust has no keyword for allocating. The allocation happens inside a method call, and the call often looks harmless. name.to_string() reads like a conversion, but it asks the allocator for memory and copies the bytes.
Learning to read code for these calls is the first step. You can then confirm each suspicion with the counting allocator.
Common sources
| Code | Allocates? | Why |
|---|---|---|
| `s.clone()` on a `String` or `Vec` | Yes | Copies the whole buffer |
| `to_string()`, `to_owned()`, `String::from(&str)` | Yes | Builds a new owned `String` from borrowed text |
| `format!(...)` | Yes | Always returns a new `String` |
| `.collect::<Vec<_>>()` | Yes | Builds a new buffer, and may regrow it |
| `Box::new(x)` | Yes | Puts the value on the heap |
| `v.push(x)` past capacity | Yes | Reallocates and moves the elements |
| `Vec::new()`, `String::new()` | No | Nothing is allocated until the first element |
| `&s[1..]`, `.iter()`, `.split_whitespace()` | No | These only borrow |
A worked example
This function allocates three times, and more if the final string has to grow:
fn label(name: &str, id: u32) -> String {
let upper = name.to_uppercase(); // allocation 1
let id_text = id.to_string(); // allocation 2
format!("{}-{}", upper, id_text) // allocation 3
}
fn main() {
println!("{}", label("disk", 7));
}id_text is not needed. format! can print an integer directly, so you can drop that step:
fn label(name: &str, id: u32) -> String {
format!("{}-{}", name.to_uppercase(), id)
}
fn main() {
println!("{}", label("disk", 7));
}This version has one fewer allocation and the same output. The remaining ones are needed here, because the function returns an owned String.
Intermediate collections
collect is the most common hidden allocation in iterator code. Compare these two functions:
fn count_long_words(text: &str) -> usize {
text.split_whitespace().filter(|w| w.len() > 5).count()
}
fn count_long_words_collected(text: &str) -> usize {
let words: Vec<&str> = text.split_whitespace().collect();
words.iter().filter(|w| w.len() > 5).count()
}Both return the same number. The second allocates a Vec to hold every word, and the first never stores them. The words themselves are &str slices into text, so the Vec buffer is the only allocation in the second version. It is not one allocation per word.
A reading checklist
When you review code, look at these places in order:
- Loops. An allocation in a loop body runs once per iteration.
- Function signatures. A parameter of type
StringorVec<T>that is only read forces callers to clone. - Calls that end in
to_*,into_*,cloneorcollect. format!used only to pass text to something that acceptsimpl Display.
Exercise
In let words: Vec<&str> = text.split_whitespace().collect();, does the code allocate once per word? What does it allocate?
Show answer
No. Each word is a &str that borrows from text, so the words are not copied. The only allocation is the Vec buffer that holds the slices, and it may be reallocated a few times as it grows.