While there’s a lot of interesting detail captured in this series, it’s often helpful
to have a document that answers some “yes/no” questions. You may not care about
Iterator looks like in assembly, you just need to know whether it allocates
an object on the heap or not. And while Rust will prioritize the fastest behavior it can,
here are the rules for each memory type:
- Smart pointers (
Mutex, etc.) allocate their contents in heap memory.
- Collections (
String, etc.) allocate their contents in heap memory.
- Some smart pointers in the standard library have counterparts in other crates that don’t need heap memory. If possible, use those.
- Everything not using a smart pointer will be allocated on the stack.
- Structs, enums, iterators, arrays, and closures are all stack allocated.
- Cell types (
RefCell) behave like smart pointers, but are stack-allocated.
- Inlining (
#[inline]) will not affect allocation behavior for better or worse.
- Types that are marked
Copyare guaranteed to have their contents stack-allocated.
constis a fixed value; the compiler is allowed to copy it wherever useful.
staticis a fixed reference; the compiler will guarantee it is unique.
« Compiler Optimizations: What It's Done Lately