- 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.
- 同步:秩序如何從混沌中涌現(xiàn)
- 有趣的二進(jìn)制:軟件安全與逆向分析
- 云計(jì)算環(huán)境下的信息資源集成與服務(wù)
- R數(shù)據(jù)科學(xué)實(shí)戰(zhàn):工具詳解與案例分析(鮮讀版)
- 醫(yī)療大數(shù)據(jù)挖掘與可視化
- Oracle高性能自動(dòng)化運(yùn)維
- OracleDBA實(shí)戰(zhàn)攻略:運(yùn)維管理、診斷優(yōu)化、高可用與最佳實(shí)踐
- 數(shù)據(jù)庫原理與應(yīng)用(Oracle版)
- Starling Game Development Essentials
- SQL優(yōu)化最佳實(shí)踐:構(gòu)建高效率Oracle數(shù)據(jù)庫的方法與技巧
- MySQL技術(shù)內(nèi)幕:SQL編程
- Unreal Engine Virtual Reality Quick Start Guide
- 企業(yè)主數(shù)據(jù)管理實(shí)務(wù)
- 數(shù)據(jù)庫應(yīng)用系統(tǒng)技術(shù)
- Unity Game Development Blueprints