[swift-users] Memory used by enums

Jens Alfke jens at mooseyard.com
Tue Apr 5 11:32:33 CDT 2016

> On Apr 4, 2016, at 4:57 PM, Jonathan Hull via swift-users <swift-users at swift.org> wrote:
> If this enum is going to be used by tens/hundreds of thousands of structs, am I actually saving any space by breaking out the rarer cases which store more data or is the footprint just equal to the largest case?

Enums are implemented a lot like C unions, so the size is equal to that of the largest case, plus a byte for the tag.

It’s interesting that the size in Daniel’s example is 41 bytes. That implies that the tag is placed at the end of the data, because putting a 1-byte field at the beginning would require 7 extra bytes of padding before the first Int. But the stride still needs to be 48 bytes to preserve the 8-byte-alignment of subsequent values.

This implies that you might be able to make an enum use up to 7 fewer bytes in practice, if you can make its largest case be one byte smaller than a multiple of a power of 2. Obviously not always attainable, but if you’re really groveling for space improvements you might be able to squeeze out that extra byte.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160405/dd9b29f6/attachment.html>

More information about the swift-users mailing list