简体   繁体   English

切换语句性能C#

[英]Switch Statement Performance C#

We're using a switch statement to do some processing on an object based on a bunch of conditions, with a default case that we expect to be called for all cases. 我们使用switch语句根据一系列条件对对象进行一些处理,我们期望在所有情况下调用默认情况。

We're having a disagreement about the best way to approach this. 我们对解决这个问题的最佳方式存在分歧。

Some of us prefer example A: 我们中的一些人更喜欢例A:

switch (task)
{
    case A:
        ProcessA();
        goto default;
    case B:
        ProcessB();
        goto default;
    case C:
        ProcessC();
        goto default;
    default:
        Final();
}

Whereas others have suggested it's better to use something like example B: 而其他人则建议使用类似B的例子:

switch (task)
{
    case A:
        ProcessA();
        break;
    case B:
        ProcessB();
        break;
    case C:
        ProcessC();
        break;
}

Final();

Since Final() will be called in all cases anyway. 因为无论如何都会在所有情况下调用Final()

Is this a case of personal preference, or are there objective performance differences. 这是个人偏好的情况,还是存在客观的性能差异。

Are there any guidelines or gotchas we should look out for? 我们应该注意哪些指导方针或问题?

This is being written in C# for an API, and will be called very frequently. 这是用C#编写的API,并且会经常调用。 We're keen to get it right! 我们渴望做对!

Cheers! 干杯!

I'd say stick with Example B. 我会说坚持做例B.

There's really no point in manually inserting code to "Jump" around. 手动插入代码到“跳转”是没有意义的。 Especially not when you're in all cases jumping to the same place. 特别是当你在所有情况下跳到同一个地方时。 This is what code blocks are for. 这就是代码块的用途。 Example B reads much better, and is much easier to follow. 示例B读取得更好,并且更容易遵循。

As for performance, I'm not sure which would be quicker (measure it?). 至于性能,我不确定哪个更快(测量它?)。 But at this point it looks like a micro optimization that you shouldn't have to care about. 但在这一点上,它看起来像一个你不应该关心的微优化。 In this example I'd say readability and maintainability trumps any minor performance gain you might get. 在这个例子中,我会说可读性和可维护性胜过你可能获得的任何微小的性能提升。

The example B is the best answer in any aspect. 示例B是任何方面的最佳答案。

Never use goto . 永远不要使用goto It reduces performance and readability for your code. 它降低了代码的性能和可读性。 CPU uses some technologies to predict future instructions to prevent performance reduction. CPU使用一些技术来预测未来的指令以防止性能降低。 Using goto will disturbs this technologies which is caused performance reduction! 使用goto会干扰这种导致性能降低的技术!

Repeating a piece of code will increase binary size of the program. 重复一段代码将增加程序的二进制大小。 So repeating Final() in all cases increases binary size of your code which is not pleasant. 所以在所有情况下重复Final()增加代码的二进制大小,这是不愉快的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM