Post

Switch vs if-else-if

In General on April 24, 2008 by Sid

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 :)

One Response to “Switch vs if-else-if”

  1. [...] Nope. If the range of the values specified in the case clauses is large, creating a table as explained previously, will cause wastage of memory. So a function like the following won’t be utilizing the IL “switch” statement and will be treated like a sequence of “if-then-else” statements. However, for efficiency, the order of comparisons might be different from the order in which “case” clauses were specified in your code (more info). [...]

Leave a Reply