1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-13 12:40:36 +02:00
comprehensive-rust/src/std/box-niche.md
2022-12-21 16:38:28 +01:00

1.2 KiB

Niche Optimization

#[derive(Debug)]
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}

fn main() {
    let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{list:?}");
}

A Box cannot be empty, so the pointer is always valid and non-null. This allows the compiler to optimize the memory layout:

 Stack                           Heap
.- - - - - - - - - - - - -.     .- - - - - - - - - - - - - - - - - - - - - - - -.
:                         :     :                                               :
:    list                 :     :                                               :
:   +--------+-------+    :     :    +--------+--------+    +--------+------+   :
:   | 0      | 1     |    :     : .->| 0      |  2     | .->| ////// | //// |   :
:   | "1/Tag"| o-----+----+-----+-'  | "1/Tag"|  o-----+-'  | "1/Tag"| null |   :
:   +--------+-------+    :     :    +--------+--------+    +--------+------+   :
:                         :     :                                               :
:                         :     :                                               :
`- - - - - - - - - - - - -'     '- - - - - - - - - - - - - - - - - - - - - - - -'