开发者

Is an empty block optimized away? C#

开发者 https://www.devze.com 2023-03-10 07:31 出处:网络
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 tha

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 thi开发者_开发知识库s away, how can I change my code so I don't have to check all the other packet ids?


The switch statement 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 if statement for just that first case and then doing a switch statement if it isn't PacketA). I would imagine that in the end the switch statement 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


Disassemble your code and check if this case is available. If it is not availablr then compiler optimized it.

0

精彩评论

暂无评论...
验证码 换一张
取 消