Niche in Arc<..> variant of enum not used by Option<..> #125363
Labels
A-layout
Area: Memory layout of types
C-optimization
Category: An issue highlighting optimization opportunities or PRs implementing such
T-compiler
Relevant to the compiler team, which will review and decide on the PR/issue.
Consider the following code (playground):
The
Foo
enum contains two niches:Foo::A(&str)
has a non-nullable field.Arc
inFoo::B(Arc<_>)
has a non-nullable field.The compiler correctly places the distinction between the variants A and B in one of these fields, concretely in the non-nullable field of the slice. The pointer for the Arc is then placed in the second half of the memory, which is otherwise the slice's length.
Unfortunately, wrapping
Foo
inOption<_>
does not make use of the remaining niche: It could set both niches to null (basically selecting the Foo::B variant and nulling the Arc's NotNull pointer) to indicate theNone
variant.Instead, we get a separate discriminant field, as can be seen by running the above example.
Note that the niche in Arc is not used at all by
Foo
. This can be seen in theBar
version of the enum, whose size does not increase by changing theArc<_>
into anOption<Arc<_>>
.I honestly have no idea about how niche tracking works and how much work it is to implement this, but I thought I'd leave this here as a kind of inspiration or tracking issue.
I note that there are a couple issues around this, but I think that this is not a duplicate of:
Missed enum layout optimization with a NonZeroU64 + more space in an enum #101567 because that discusses the use of multiple niches within the same enum, which I understand has invisible performance drawbacks (needs more than one load to understand which variant we're looking at).
I think that does not apply because
Option<Foo>
, as it stands, also needs two loads to figure out whichFoo
variant (if any) we're looking at: One to see if the Option is None, and a second one to see if the slice's ptr is null (Foo::B
) or not (Foo::A
).Missed layout optimisation with multiple niches #119507 could be related, but it's about structs. Not sure if that qualifies as dup.
Enums don't utilize niches across multiple data-carrying variants #121333 seems to be about attempting to exploit "opposite" niches in order to unify types.
Thank you for reading.
The text was updated successfully, but these errors were encountered: