Florian Greinacher
Florian Greinacher

Reputation: 14784

Performance of enum conversion

after a bit speedtracing I found a piece of code (called very very often) which converts values of one enum to values of another enum, like this:

public Enum2 ConvertToEnum2(Enum1 enum1)
{
   switch(enum1)
   {
      case Enum1.One:
         return Enum2.One;
         break;
      case Enum1.Two:
         return Enum2.Two;
         break;
   }
}

Would it me more performant if I save those conversions in a Dictionary and just do something like this:

public Enum2 ConvertToEnum2(Enum1 enum1)
{
   return m_ConversionTable[enum1];
}

Thanks for your comments!

Upvotes: 1

Views: 1235

Answers (3)

oefe
oefe

Reputation: 19926

This will likely depend on your enums. For small enums, I would expect that a switch is likely the fastest method, while for very large enums, a dictionary lookup might be faster.

To get a definitive answer, you will have to measure it, using your enums.

Upvotes: 1

ggf31416
ggf31416

Reputation: 3647

Are you sure that it's a botteneck? I found that many profilers report incorrect time percentages for small methods.
In my computer I can execute 100 millons conversions between enums with 10 elements in 1.7 seconds using a switch (Anthony's answer is 10 time faster).

Upvotes: 3

AnthonyWJones
AnthonyWJones

Reputation: 189555

A dictionary definitely would not be faster.

If the enums in the Enum1 are sequential then an array of Enum2 would likely be faster (but that could be marginal). IF the Enum1 is close to sequential so that the array isn't too spares it may still be useful approach.

For an enum with the [Flags] attribute then the switch is probably the best.

Upvotes: 5

Related Questions