[Mono-list] [Off-topic] "if else" or "switch" ?

Marcus mathpup@mylinuxisp.com
Fri, 15 Oct 2004 17:39:01 -0500


Performance will depend on both the C# compiler used and the runtime/JIT. I 
have not tested four-way decisions, which is what you have, but I did test 
three-way decisions not too long ago.

With Mono's C# compiler + mono runtime, if-statements were about 3 times 
faster than switch. Interestingly, with Portable.NET's C# compiler, 
if-statements and switch performed almost identically to each other (and to 
Mono's C# if-statement version). So Mono's C# compiler is definitely not 
producing the best code for the mono-runtime. 



On Friday 15 October 2004 9:35 am, Fabien Meghazi wrote:

> I was wondering if mono would generate diferent code between a "switch"
> and an "if else suite". I guess yes.
> But I would like to know wich of the two code would be faster ?
> (I know we are speaking of a few cpu cycles of difference, but I would like
> to know anyway) I would have benchmark this but I've nothing to do this,
> and I guess that this question could be theorically answered easily by
> those how put their hand in mono compiler.
>
> So which of those two methods generate faster code ?
> PS: orientation is a string and the following code is in a for loop :
> // --> for (int i = 0; i < orientation.Length; i++)
>
> Method 1
> *************************************
>     switch (orientation[i]) {
>      case 'l':
>       left = true;
>       break;
>      case 'r':
>       left = false;
>       break;
>      case 't':
>       top = true;
>       break;
>      case 'b':
>       top = false;
>       //break;
>     }
>
>
> Method 2
> *************************************
>     char or = orientation[i];
>     if (or == 'l') left = true;
>     else if (or == 'r') left = false;
>     else if (or == 't') top = true;
>     else if (or == 'b') top = false;