- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 197字
- 2021-07-02 14:11:49
Heaps and stacks
As we discussed in Chapter 1, Hello Rust!, stack variables are preferred thanks to their low overhead and speed compared to heap-allocated data, which automatically introduces overhead thanks to the necessary heap pointer. For stack variables, Rust's types even allow for zero overhead structures, so no additional metadata is stored. The following snippet asserts that there are no additional bytes being used for arrays or user-defined types:
use std::mem;
struct MyStruct {
a: u8,
b: u8,
c: u8
}
fn main() {
assert_eq!(mem::size_of::<MyStruct>(), 3 * mem::size_of::<u8>());
assert_eq!(mem::size_of::<[MyStruct; 2]>(), 3 * mem::size_of::<u8>() * 2);
}
Consequently, the size of an instance of the MyStruct type is always going to be three bytes—perfectly suitable for placing it on the stack. Why is that good? In short, data locality. Instead of pointer dereferencing, the data is stored right at the point of execution, making it easy to cache and fast to access.
Types that don't have predictable sizes (such as String instances) require heap allocation, just like objects that are wrapped into Rc, Cell, RefCell, or Box instances. However, heap allocations and access come at a considerable cost, as minimizing those typically yields great performance improvements.