2019-02-09 23:21:25 -05:00
|
|
|
---
|
|
|
|
layout: post
|
2019-02-10 22:45:55 -05:00
|
|
|
title: "Summary: What are the Allocation Rules?"
|
2019-02-09 23:21:25 -05:00
|
|
|
description: "A synopsis and reference."
|
2020-06-29 15:51:23 -04:00
|
|
|
category:
|
2019-02-09 23:21:25 -05:00
|
|
|
tags: [rust, understanding-allocations]
|
|
|
|
---
|
|
|
|
|
2020-06-29 16:00:26 -04:00
|
|
|
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 what an `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:
|
2019-02-09 23:21:25 -05:00
|
|
|
|
|
|
|
**Heap Allocation**:
|
2020-06-29 15:51:23 -04:00
|
|
|
|
2019-02-09 23:21:25 -05:00
|
|
|
- Smart pointers (`Box`, `Rc`, `Mutex`, etc.) allocate their contents in heap memory.
|
|
|
|
- Collections (`HashMap`, `Vec`, `String`, etc.) allocate their contents in heap memory.
|
2020-06-29 16:00:26 -04:00
|
|
|
- Some smart pointers in the standard library have counterparts in other crates that don't need heap
|
|
|
|
memory. If possible, use those.
|
2019-02-09 23:21:25 -05:00
|
|
|
|
|
|
|
**Stack Allocation**:
|
2020-06-29 15:51:23 -04:00
|
|
|
|
2019-02-10 22:44:40 -05:00
|
|
|
- Everything not using a smart pointer will be allocated on the stack.
|
2019-02-09 23:21:25 -05:00
|
|
|
- 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 `Copy` are guaranteed to have their contents stack-allocated.
|
|
|
|
|
|
|
|
**Global Allocation**:
|
2020-06-29 15:51:23 -04:00
|
|
|
|
2019-02-09 23:21:25 -05:00
|
|
|
- `const` is a fixed value; the compiler is allowed to copy it wherever useful.
|
|
|
|
- `static` is a fixed reference; the compiler will guarantee it is unique.
|
|
|
|
|
2020-06-29 16:00:26 -04:00
|
|
|
![Container Sizes in Rust](/assets/images/2019-02-04-container-size.svg) --
|
|
|
|
[Raph Levien](https://docs.google.com/presentation/d/1q-c7UAyrUlM-eZyTo1pd8SZ0qwA_wYxmPZVOQkoDmH4/edit?usp=sharing)
|