mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-07 18:16:15 +02:00
Fix example of niche optimization in Smart Pointers / Box<T> (#1946)
Example with linked list replaced by example with Option
This commit is contained in:
parent
6064631f50
commit
b38d429e49
@ -89,34 +89,32 @@ fn main() {
|
|||||||
|
|
||||||
## Niche Optimization
|
## Niche Optimization
|
||||||
|
|
||||||
|
Though `Box` looks like `std::unique_ptr` in C++, it cannot be empty/null. This
|
||||||
|
makes `Box` one of the types that allow the compiler to optimize storage of some
|
||||||
|
enums.
|
||||||
|
|
||||||
|
For example, `Option<Box<T>>` has the same size, as just `Box<T>`, because
|
||||||
|
compiler uses NULL-value to discriminate variants instead of using explicit tag
|
||||||
|
(["Null Pointer Optimization"](https://doc.rust-lang.org/std/option/#representation)):
|
||||||
|
|
||||||
```rust,editable
|
```rust,editable
|
||||||
#[derive(Debug)]
|
use std::mem::size_of_val;
|
||||||
enum List<T> {
|
|
||||||
Element(T, Box<List<T>>),
|
struct Item(String);
|
||||||
Nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let list: List<i32> =
|
let just_box: Box<Item> = Box::new(Item("Just box".into()));
|
||||||
List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
|
let optional_box: Option<Box<Item>> =
|
||||||
println!("{list:?}");
|
Some(Box::new(Item("Optional box".into())));
|
||||||
|
let none: Option<Box<Item>> = None;
|
||||||
|
|
||||||
|
assert_eq!(size_of_val(&just_box), size_of_val(&optional_box));
|
||||||
|
assert_eq!(size_of_val(&just_box), size_of_val(&none));
|
||||||
|
|
||||||
|
println!("Size of just_box: {}", size_of_val(&just_box));
|
||||||
|
println!("Size of optional_box: {}", size_of_val(&optional_box));
|
||||||
|
println!("Size of none: {}", size_of_val(&none));
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A `Box` cannot be empty, so the pointer is always valid and non-`null`. This
|
|
||||||
allows the compiler to optimize the memory layout:
|
|
||||||
|
|
||||||
```bob
|
|
||||||
Stack Heap
|
|
||||||
.- - - - - - - - - - - - - - . .- - - - - - - - - - - - - -.
|
|
||||||
: : : :
|
|
||||||
: list : : :
|
|
||||||
: +---------+----+----+ : : +---------+----+----+ :
|
|
||||||
: | Element | 1 | o--+----+-----+--->| Element | 2 | // | :
|
|
||||||
: +---------+----+----+ : : +---------+----+----+ :
|
|
||||||
: : : :
|
|
||||||
: : : :
|
|
||||||
'- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - -'
|
|
||||||
```
|
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user