The enum optimization

If you are programming C# (yes, and even C/C++) you are most probably familar with the enum construction.  Instead of using “magic-numbers” in your code, you increase the readability and maintainability by using enums.  E.g.:

 

public enum CompanyType
{
  Unknown,
  Inc,
  DBA,
  LLC,
  LLP,
  LP,
  PLLC,
  SoleProprietorship
}

The enumeration above is declared without values to hold different types of business entities, as normally you don’t care about the values behind.  This makes code look a lot more readble in contrast to just using magic numbers or variables instantiated with constants.

But have you ever thought about how it is internally represented in the computer memory?  If not, let me tell you:  It is stored as a 4-byte value on the stack.   So consider if you have e.g. a Company class where one property is of the CompanyType enum.  We need to hold an array of companies of at least 50.000 in memory.   This will take up 50.000 x 4 = 200.000 bytes.   But our enumeration only consists of 8 values, where one byte should be more than addequite!
Giving us a total memory waste of 50.000 x 3 = 150.000 bytes.  That’s not very good, so you’d probably wish you could specify the type (and thereby how much memory the enumeration would use) … and guess what … you can.

 

public enum CompanyType : byte
{
  Unknown,
  Inc,
  DBA,
  LLC,
  LLP,
  LP,
  PLLC,
  SoleProprietorship
}

and voilá the enumeration is declared to use a byte.