Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which has better performance, Enum or Int in a switch case?

Which code snippet is better to use when considering the performance for the switch case with enum and int as the case parameter:

A.

switch ((ToolbarButton)BtnId)
{
    case ToolbarButton.SHOWPROPERTYDIALOG:
         OnShowProperties();
         break;
    case ToolbarButton.MOVETOFIRST:
         OnFirstMessage();
         break;
    case ToolbarButton.MOVETOLAST:
         OnLastMessage();
         break;
}

B.

switch (BtnId)
{
     case (int)ToolbarButton.SHOWPROPERTYDIALOG:
          OnShowProperties();
          break;
     case (int)ToolbarButton.MOVETOFIRST:
          OnFirstMessage();
          break;
     case (int)ToolbarButton.MOVETOLAST:
          OnLastMessage();
          break;
}
like image 275
Kris Avatar asked Jul 17 '12 05:07

Kris


People also ask

Why is enum faster?

Enums will usually use 4 bytes - their underlying type defaults to int unless you explicitly declare otherwise. The "greatly outperform" part depends largely on what you're doing with the enum once you get it. If you use it in a switch statement, enums will be faster.

Is enum fast?

You shouldn't be using enum.Much, much faster than comparing strings. The only real time you'll have to have the string representation of an enum is if you're populating a drop down list or something similar, and for that you ToString each item once and you're done with it.

Can enums be used in switch statements?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

Can enum be used in switch case in C?

Example of Using Enum in Switch Case Statement We will then use the switch case statements to switch between the direction elements and print the output based on the value of the variable for the enum directions.


2 Answers

Once compiled, Enums ARE Ints.

There is No difference what-so-ever in the MSIL.

like image 98
abelenky Avatar answered Oct 27 '22 00:10

abelenky


When compiling, the JIT replaces Enums with Int32 type. This is known as inline replacement and hence there is no performance hit. I would prefer using Enums as they increase readability and can be back-tracked (Find Reference) as well.

like image 35
GeekzSG Avatar answered Oct 27 '22 00:10

GeekzSG