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

Viewed 147

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?

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.

Related