rust icon indicating copy to clipboard operation
rust copied to clipboard

Niche optimisation with disjoint tags

Open robertbastian opened this issue 3 years ago • 2 comments

These two types could be laid out the same. However, the second type makes it explicit that the tag is logically split across different bytes. Is this something we'd be okay with the compiler doing on its own? Inspecting the next part of the tag might require an extra load.

enum ShortSlice<T> {
    Empty,
    Single(T),
    Multi(Box<[T]>),
}
dbg!(size_of::<ShortSlice<NonZeroUsize>>()); // 24

enum ShortSlice2<T> {
    ZeroOne(Option<T>),
    Multi(Box<[T]>),
}

dbg!(size_of::<ShortSlice2<NonZeroUsize>>()); // 16

https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=a15d6b9d5389d781c5d778b250a02627

robertbastian avatar Oct 13 '22 01:10 robertbastian

@mikebenfield

robertbastian avatar Oct 13 '22 16:10 robertbastian

How does the compiler determine that this sort of optimization should be done for Option?

jruderman avatar Oct 17 '22 06:10 jruderman