简体   繁体   中英

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.

We're having a disagreement about the best way to approach this.

Some of us prefer example 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:

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

Final();

Since Final() will be called in all cases anyway.

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. We're keen to get it right!

Cheers!

I'd say stick with Example 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.

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.

Never use goto . It reduces performance and readability for your code. CPU uses some technologies to predict future instructions to prevent performance reduction. Using goto will disturbs this technologies which is caused performance reduction!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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