[swift-users] Memory used by enums

Joe Groff jgroff at apple.com
Tue Apr 5 12:55:06 CDT 2016

> On Apr 4, 2016, at 4:57 PM, Jonathan Hull via swift-users <swift-users at swift.org> wrote:
> I had a quick question on the memory used by enums with associated values in the current implementation.  If I have an enum like the following:
> enum MyEnum {
> 	case mostCommonlyUsed
> 	case somewhatCommon (Int,Int)
> 	case prettyRare (Int,Int,Int,Int,Int)
> }
> 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?

The payloads are stored in-line by default, so yeah, the enum will be the size of its largest payload, possibly with extra space for tag bits if there's nowhere to cram the bits in the payload otherwise. You can mark your large, rare cases `indirect`, which will make the inline storage pointer-width, referencing a separate allocation:

enum MyEnum {
	case mostCommonlyUsed
	case somewhatCommon (Int,Int)
	indirect case prettyRare (Int,Int,Int,Int,Int)


More information about the swift-users mailing list