Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Android Events why are switch statements more common than if-else chains?

When developing for Android is a switch statement more efficient than an if-else chain? A switch statement takes more lines of code, but looking at anecdotal evidence seems to be the more commonly used in Android applications.

The examples below illustrate the same programming construct with a case statement and if-else chain. The switch statement requires 10 lines while the if-else chain requires 7.

Case Statement

public void onClickWithSwitch(View v) {
   switch(v.getId()) {
       case R.id.buttonA:
           buttonA();
           break;
       case R.id.buttonB:
           buttonB();
           break;
       case R.id.buttonC:
           buttonC();
   }
}

If-else chain

public void onClickWithIf(View v) {
   int id = v.getId();
   if(id == R.id.buttonA)
       buttonA();
   else if (id == R.id.buttonB)
       buttonB();
   else if (id == R.id.buttonC)
       buttonC();
}

Why would switch be more common than an if-else chain? Do switch statements offer better performance when compared to if-else chains?

like image 785
700 Software Avatar asked Jan 21 '11 16:01

700 Software


1 Answers

The reason languages have switch statements is to allow the compiler to generate a jump table, which is fast if it's large, because at run-time it can get to the desired code in O(1) rather than O(N) time.

It's only helpful speed-wise if there are many cases and the code to execute in each case does not take much time, and the program spends much percentage of time in this code at all.

Other than that it's purely a matter of taste.

There is no relationship between number of code lines and speed. What matters is the kind of assembly language code that's generated, which I'd encourage you to get familiar with.

like image 164
Mike Dunlavey Avatar answered Sep 23 '22 17:09

Mike Dunlavey