# Thread: SWITCH and ARRAY which is efficient?

1. ## SWITCH and ARRAY which is efficient?

Which is the most efficient code in the below two, and why?

In the below code X123 can have values X0, X1, X2 and X3 only.

Code:
```switch(X123)
{  case 0:
var1 = X0;
break;
case 1:
var1 = X1;
break;
case 2:
var1 = X2;
break;
case 3:
var1 = X3;
break;

}```
[\code]

In the below code rewritten we use X[3] inatead of X0, X1...

Code:
```If (X123 <= 3)
{          var1= X[X123];
}```

2. The switch statment in this case is more efficient. Sometimes it's a decision of how elegent you want your code to look, or how elegent you want to solve a problem.

3. Here my concern is the run time.

4. With any modern day computer...Unless you have like thousands of lines of comparison statements...it won't matter too much. What is the actual program you are implementing the switch statement in?

5. I would use whatever method you think is the easiest to understand. You should not worry about execution time until you have determined that you have a bottleneck. Premature optimization usually will just add complexity to your program with no real performance gain.

Jim

6. Originally Posted by jimblumberg
I would use whatever method you think is the easiest to understand. You should not worry about execution time until you have determined that you have a bottleneck. Premature optimization usually will just add complexity to your program with no real performance gain.

Jim
Ha-ha, Just listen to Jim...

7. Originally Posted by DuckCowMooQuack
Ha-ha, Just listen to Jim...
Thanx Guys

8. When it comes to run-time performance, lookup tables FTW! Shorter and likely faster. Having said that, if it matters at all - profile!
Unless of course it is very important to stress that a value of 2 must be translated exactly into a value of X2 and not X1 say. I.e. in a long lookup table you cant easily see which input value translates to a certain output value. Then a switch table can be used for clarity.
Often though, this is not important. Lookup tables are preferred in cases where say e.g. you want to select a random entry from a list of strings. The ordering of the table entries does not matter and using a switch statement would be longer, likely slower, and convey superflous information.

9. I wouldn't be surprised if the compiler turned the switch statement into the array lookup on its own.

You could profile it, but that doesn't tell you much, because modern CPUs are so complicated that the switch might be faster on one specific processor and slower on some other processor. Chances are they are not very much different anyway.

Write the code to be clear. If and only if you then discover that it's not fast enough, use a tool -- do not guess -- to figure out where the bottleneck is and try to optimize it. Do experiments, don't just guess.