Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to know switch performance C#

Suppose there is a switch on some method like

static string switchExample(string abc){
    switch(abc.ToUpper()) {
        case "123":
            return "Numeric";
        case "ab":
            return "Alphabets";
        default:
            return "symbol";
    }
}

Now here I need to know if there are any performance issues to use multiple points of exit(return on each case) like I did in given code rather to pass updated value at one time by making some temp string at the start and filling it with corresponding case match.

like image 541
RollerCosta Avatar asked Feb 22 '23 02:02

RollerCosta


1 Answers

Now here i need to no is there any performance issue to use multiple points of exit

Your question is the epitome of premature optimization.

My suggestion, if you really want to know, is to write the method out both ways - once with return statements in each case and once with a single return after the switch statement. Then decompile each to intermediate language for comparison.

You still won't be able to make any certain statement about performance without doing actual measurement by profiling.

But, I think it's quite safe to say that any difference, if any, will be extremely miniscule. The end result should be nothing more than comparing the value to the constant strings, and when matched pushing the value and the stack and returning. The compiler will likely optimize away the assignment to a temporary variable, seeing that it will only be used as a return value.

Furthermore, some switch statements are significantly optimized by the compiler. See https://stackoverflow.com/a/395965/224087 and https://stackoverflow.com/a/126507/224087 for more information of switch statement performance and optimization.

This code you are questioning the performance of will only be a handful or two of CPU operations - a truly tiny amount of time to be concerned with.

like image 92
quentin-starin Avatar answered Feb 24 '23 15:02

quentin-starin