Sub-optimal layout of Option<(u16, [u8; 15])>
(missed niche optimization)
#117429
Labels
A-layout
Area: Memory layout of types
C-enhancement
Category: An issue proposing an enhancement or a PR with one.
T-compiler
Relevant to the compiler team, which will review and decide on the PR/issue.
I tried this code:
I expected to see this happen:
(u16, [u8; 15])
has a size of 18 bytes, because there are 17 bytes of useful data and it is rounded up due to the alignment of 2 bytes.Option<(u16, [u8; 15])>
to also take 18 bytes due to a niche optimization.Instead, this happened:
Option<(u16, [u8; 15])>
takes 20 bytes, and appears to be layout as:I expected the Option to leverage the byte of padding at the end of the struct to decide if it's
None
orSome
instead of pre-pending a discriminant.Meta
Tested on the playground: https://play.rust-lang.org/?version=stable&mode=release&edition=2021
This is inspired by the
tinyvec
crate, which is roughly layout as follows (https://docs.rs/tinyvec/latest/src/tinyvec/tinyvec.rs.html#97-103, https://docs.rs/tinyvec/latest/src/tinyvec/arrayvec.rs.html#103-107) - although the niche wouldn't apply in that case (and thesmallvec
crate has a better layout):The text was updated successfully, but these errors were encountered: