views:

261

answers:

3

Hi folks,

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!

+5  A: 

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.

AnthonyWJones
If the enums are close, the optimizer is likeyl to implement a jump table, so in that case the switch would be better, too. (Don't know if C#/.NET actually does that, though, but it is a common optimization)
peterchen
@peterchen: Like said its marginal, jump table takes code execution to a point of code which then returns a value. An array lookup would be comparable to the jump table look but there is no return to process. Once optimised I doubt there would be much difference.
AnthonyWJones
+3  A: 

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).

ggf31416
+1  A: 

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.

oefe