Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing enum in array VS storing in dictionary?

Tags:

c#

Assume I have some enum. For example

enum MyEnum
{ 
    Item1, 
    Item2, 
    Item3
}

I want to "cache" something for each item in the enum. So I do have two options.

Dictionary option:

Dictionary<MyEnum, /*someStructure*/> cache = new Dictionary<MyEnum, /*someStructure*/>>();

or Array option:

/*someStructure*/[] cache = new /*someStructure*/[Enum.GetValues(typeof(MyEnum)).Length]

What are prons and cons of each of these options? In my opinion Dictionary option is more readable and easy to use, but slower than Array option.

But will Dictionary actually be slower? Probably Dictionary is "smart" enough to understand that when enum is used as a key, then just "array" can be used as underling implementation?

So the question is - will "ugly array option" be faster than "straightforward" Dictionary option? Well probably I can just test that... But now when I've wrote the question I want to know what others think.

like image 220
Oleg Vazhnev Avatar asked Mar 06 '26 21:03

Oleg Vazhnev


1 Answers

Dictionany<TKey, TValue> isn't "smart" and doens't optimize for any given key. The underlighing implementation is always the same.

However, about performance, using enum values as key in dictionary is much slower than you might expect, and is much slower than storing Int32 as the key. The reason for this is because the runtime uses heavy reflection to get the hash code of an enum when calling GetHashCode(). This if actually found quite bizar.

But all of this doesn't matter when the most readable approach (using the enum as key in a dictionary) is fast enough. And nobody here can answer that question for you. You will have to measure this. Don't do premature optimization and go with the most readable/maintainable pease of code until proven that the solution isn't fast enough for in your situation (which it will probably be).

However, instead of switching to an array, try switching to a dictionary with a Int32 key:

var dictionary = new Dictionary<int,  /*someStructure*/>();

dictionary[(int)MyEnum.Item1] = /*new someStructure()*/;
like image 175
Steven Avatar answered Mar 08 '26 11:03

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!