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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With