In most languages with switch
statements, switch
is a special form designed such that the possibilities are evaluated lazily and the compiler knows how to optimise the selection of statements based on the given input. R, mostly already being lazy, does not need some of this. However, R's switch
statement is still a function call, rather than any sort of special form. Does this mean that R's switch
statement is slower than it would be if it were a special form? Or does R's interpreter know to optimise it as if it were a special form?
On the other hand, a switch statement works comparatively faster because the compiler generates a jump table for switch-cases during compile time. So when the code runs, instead of checking which cases are satisfied, it only decides which cases should be executed.
Most would consider the switch statement in this code to be more readable than the if-else statement. As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large.
Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too.
The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.
If you look at internal code of switch
in file src/main/builtin.c, you can read in lines 1009-1025 :
This is a SPECIALSXP, so arguments need to be evaluated as needed.
SPECIALSXP
means :
no SEXPTYPE Description
7 SPECIALSXP special functions
So switch
is actually a special function which passes unevaluated arguments to the internal function.
Further reading the source code from line 1030 to line 1104 shows that as explained in ?switch
, the function either handles character
or number
in a simple and not fully optimized way.
This probably explains why switch
isn't particularly fast in situations which would for example require a binary search.
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