Coming from some code I got on the internet, I got to wonder whether there is some option to set, to optimize the bytecode compiler. Documentation of compiler::cmpfun says there is an optimization level, that can be set with the "option" parameter (but how?) and that has already the value of 2 from a range from 0 to 3, which seems rather high.
But in my example, optimization seems very poor. The display below is just some post processing around the output of the compiler::disassemble function, in order to make the things more pretty. As the disassembly says, it tries to do z <- z which doesn't make much sense. It could make sense if z was an active binding but it is obviously not the case.
f <- function (x) {z <- 0; z <- if (x==42) 0 else z; x}
f <- compiler::cmpfun(f)
purrr::walk(dasm(f),function(x) message(paste(x,collapse=' ')))
## LDCONST.OP 1 # the constant 0
## SETVAR.OP 3 # z bound to it (3 must be some kind of location for z)
## POP.OP # ignore result of <-
## GETVAR.OP 5 # the value of x
## LDCONST.OP 7 # the constant 42
## EQ.OP 8 # test for equality
## BRIFNOT.OP 9 19 # if not eq, goto step (2)
## LDCONST.OP 10 # else (eq), the constant 0
## GOTO.OP 21 # and goto step (3)
## GETVAR.OP 3 # step 2(eq): get the value of z
## SETVAR.OP 3 # and set z to be a reference
## POP.OP # and ignore the result of <-
## GETVAR.OP 5 # step 3: get the value of x
## RETURN.OP # and return it as the result of f
I saw other related questions on SO, but without any beginning of answer for mine, probably because these answers are a bit old, from a era where compiling was not so frequent...