0

It is a basic doubt, I didn't get any proper answer from my search. In android which condition statement is more faster? If or Switch and what is the reason?. Android Coding guideline itself suggest Switch instead of If. Please clarify my doubt.

EKN
  • 1,886
  • 1
  • 16
  • 29
  • 2
    also [What is the relative performance difference of if/else versus switch statement in Java?](https://stackoverflow.com/questions/2086529/what-is-the-relative-performance-difference-of-if-else-versus-switch-statement-i) – bansi May 27 '17 at 06:36

2 Answers2

5

Which to choose Switch or if?

There are a few reasons why I would consider using a switch instead of if.Actually it depends.

1. Speed

A switch statement might be faster than if. I write might because it depends on your use case.it's able to generate something like value -> function to call for every value in your range and figure out the code path using one lookup. This is generally faster than the instructions generated for a chain of if, as every expression in the if is evaluated separately.

2. Easy maintenance

A switch looks much cleaner when you have to combine cases. If will quickly get out of control. Easy to add new cases in switch compare to if.

One more important point is Neither if-else or switch are direct assembly statements. So it depends on the way compiler converts the code to assembly.

Write the code in the most readable fashion and let the compiler take care of the rest. Compilers generally convert swith statements into lookup table giving some advantage. As against that if you have some "likely" and "unlikely" conditions

Lokesh Desai
  • 2,607
  • 16
  • 28
3

Technically, this question is in fact a duplicate of the suggested question, but the answers in the suggested question are kind of bad, so I will re-answer it.

The reason why switch is faster than if is because:

  • switch guarantees that the expression to be checked will be evaluated only once, while a sequence of cascaded ifs may re-evaluate the expression once for each if if the expression involves a term that the compiler cannot safely assume that it will stay unchanged during repeated evaluations, as the case is when, for example, the expression involves a virtual method call.

  • switch is implemented using a special bytecode which is implemented in a very efficient way by the VM. I cannot give any guarantees as to precisely how any VM implements this bytecode, but I have seen C++ compilers decades ago doing things as smart as performing a binary search over the table of switch label values, and I have no reason to believe that modern VMs are not at least as smart.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142