-
-
Save allwelldotdev/f5aafb7c6b75509cdacbabb5f5f335c6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Niche optimization | |
| // A clever way to make Option<T> (or similar enums) use the exact same memory | |
| // size as T itself, without wasting space for a "tag" | |
| // (like a boolean for Some/None). | |
| use std::mem::{size_of, MaybeUninit}; | |
| fn main() { | |
| // Seeing the size overhead of using Option types | |
| println!("size_of::<i32>(): {}", size_of::<i32>()); | |
| println!( | |
| "size_of::<Option<i32>>(): {}", | |
| size_of::<Option<i32>>() /* `i32` can be a zero value (0) | |
| therefore Niche optimization cannot work here. Instead | |
| `None` will be given another byte size. */ | |
| ); | |
| // The size of a pointer (& and &mut) is usize. | |
| println!("---\nsize_of::<&i32>(): {}", size_of::<&i32>()); | |
| println!( | |
| "size_of::<Option<&i32>>(): {}", | |
| size_of::<Option<&i32>>() /* Niche optimization. Why does it | |
| work here and not in `Option<i32>` because a pointer (& or &mut) | |
| cannot be null or zero. */ | |
| ); | |
| println!("size_of::<usize>(): {}", size_of::<usize>()); | |
| println!("---"); | |
| // No overhead with MaybeUnint types; as types are uninitialized | |
| println!("size_of::<i32>(): {}", size_of::<i32>()); | |
| println!( | |
| "size_of::<MaybeUninit<i32>>(): {}", size_of::<MaybeUninit<i32>>() | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment