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;
}
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.
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.
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
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.
Once compiled, Enums
ARE Ints
.
There is No difference what-so-ever in the MSIL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With