I am developing a game server in C# and a specific packet gets sent to my server 3 to 5 times per second per player. We will call that packet PacketA. I don’t do anything with it except make sure that I receive it.
Since this packet gets sent the most, I want to place it first in the switch block so I don’t have to make so many unnecessary comparisons. Will the compiler end up optimizing it away anyways (which will cause me to make all the comparisons down the switch block?)
switch (packetId)
{
case PacketID.PacketA: // I do not want to do anything here.
break; // Just avoid all other packet id comparisons.
case PacketID.PacketB:
HandlePacketB(data);
break;
case PacketID.PacketC:
HandlePacketC(data);
break;
// ...
case PacketID.PacketZ:
HandlePacketZ(data);
break;
}
If the compiler does optimize this away, how can I change my code so I don’t have to check all the other packet ids?
The
switchstatement in C# is optimized in a way that allows for a very quick evaluation of where to go. It doesn’t read down through the list of options exactly. Instead it creates a jump list that it optimized for identifying which case to execute. Here is a link with more information about it:http://www.dotnetperls.com/switch-char
Basically, I would suggest that you test the performance of this statement compared to another statement (such as doing an
ifstatement for just that firstcaseand then doing aswitchstatement if it isn’tPacketA). I would imagine that in the end theswitchstatement is the way to go.If you decide that you want to dig into your app by decompiling it, you can use the new (free) tool from Telerik:
http://www.telerik.com/products/decompiling.aspx