Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R's switch statement is not a special form, is it therefore slow?

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?

like image 477
J. Mini Avatar asked Jan 25 '21 13:01

J. Mini


People also ask

Are switch statements Slow?

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.

Are switch statements faster?

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.

Is switch case faster than if C?

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.

What is the purpose of the switch statement?

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.


1 Answers

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.

like image 106
Waldi Avatar answered Oct 24 '22 09:10

Waldi