Quantcast
Channel: switch/case with string
Viewing all articles
Browse latest Browse all 13

switch/case with string

$
0
0
 Peter Ritchie wrote:

I see nothing to do with hash tables when reflecting a switch statement.  It performs the same instructions as if would (ldloc, ldstr, call System.StringStick out tongue_Equality), the only difference is with a switch statement a branch is generated next, with an if generates two instructions to test the result for 0.

 

Here's if(text == "one"):

  L_002d: ldloc.0
    L_002e: ldstr"one"
    L_0033: callbool [mscorlib]System.String::op_Equality(string, string)
    L_0038: ldc.i4.0
    L_0039: ceq
    L_003b: stloc.2
    L_003c: ldloc.2
    L_003d: brtrue.s L_004d

Here's switch(text) case "one":

  L_0058: ldloc.0
    L_0059: stloc.3
    L_0060: ldloc.3
    L_0061: ldstr"one"
    L_0066: callbool [mscorlib]System.String::op_Equality(string, string)
    L_006b: brtrue.s L_00b0

The switch stores a temporary reference to the "text" variable in a local (in case it changes while switching) hence the ldloc.3 instead of ldloc.0.  So, it appears the code generated for a switch comparison is more efficient than an if.  Which is probably moot by the time the JIT optimizes it.
That was in debug mode.  In release mode the code is far more optimized and using if/elseif and a switch with two case: the if/elseif is 5 instructions less than the switch.  Again, probably moot once the JIT optimizes.

Viewing all articles
Browse latest Browse all 13

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>