Constant Folding and Propagation

f <- function(n) {
  a <- 30
  b <- 9 - (a / 5)
  c <- b * 4
  if (c > 10) {
     c <- c - 10
  }
}

# # After one step
# f_opt <- function(n) {
#   a <- 30
#   b <- 9 - (30 / 5) # replace a for its value
#   c <- b * 4
#   if (c > 10) {
#      c <- c - 10
#   }
# }

# # After two steps
# f_opt <- function(n) {
#   a <- 30
#   b <- 3 # calculate value of b
#   c <- b * 4
#   if (c > 10) {
#      c <- c - 10
#   }
# }

# # After three steps
# f_opt <- function(n) {
#   a <- 30
#   b <- 3
#   c <- 3 * 4 # replace b for its value
#   if (c > 10) {
#      c <- c - 10
#   }
# }

# # After four steps
# f_opt <- function(n) {
#   a <- 30
#   b <- 3
#   c <- 12 # calculate value of c
#   if (c > 10) {
#      c <- c - 10
#   }
# }

# # After five steps
# f_opt <- function(n) {
#   a <- 30
#   b <- 3
#   c <- 12
#   if (12 > 10) { # replace c fot its value
#      c <- 12 - 10 # replace c fot its value
#   }
# }

# After six steps
f_opt <- function(n) {
  a <- 30
  b <- 3
  c <- 12
  if (TRUE) { # evaluate constant value
     c <- 2 # evaluate constant value
  }
}

f_c <- cmpfun(f)
f_opt_c <- cmpfun(f_opt)
n <- 10000
autoplot(microbenchmark(f(n), f_c(n), f_opt(n), f_opt_c(n)))