Switch vs if-else-if

Posted on April 24, 2008

1


This is an academic question. Which one is better?

private string Foo(int value) { string result; switch (value) { case 10: result = "something 1"; break; case 110: result = "something 2"; break; case 150: result = "something 3"; break; case 210: result = "something 4"; break; default: result = string.Empty; break; } return result; }

or

private string Bar(int value) { string result; if (value == 10) result = "something 1"; else if (value == 110) result = "something 2"; else if (value == 150) result = "something 3"; else if (value == 210) result = "something 4"; else result = String.Empty; return result; }

Even though both Foo and Bar do the same thing, Foo is better performance wise.

The compiler converts Foo into IL which roughly achieves the same thing as the following pseudo-code.

if value < 110 then if value == 10 then result = "something 1" else goto default_case else if value == 110 then result = "something 2" else if value == 150 then result = "something 3" else if value == 210 then result = "something 4" else default_case: result = String.Empty end if

Foo when converted to IL splits the search space with 110 in the middle which reduces the number of comparisons needed. As a result Foo will be faster than Bar. However, I wouldn’t advise you to worry about performance at this scale. As I said in the beginning, this question was only academic :)

Advertisement
Posted in: General