f <- function(n) {
y <- 1
z <- 1
a <- vector("numeric", n)
for (i in seq_len(n)) {
x <- y + z # invariant line inside the loop (can be taken outside)
a[i] <- 6 * i + x * x # invariant expression (can be calculated outside)
}
}
f_opt <- function(n) {
y <- 1
z <- 1
a <- vector("numeric", n)
x <- y + z # outside of the loop
t1 <- x * x # new var, and outside of the loop
for (i in seq_len(n)) {
a[i] <- 6 * i + t1
}
}
f_c <- cmpfun(f)
f_opt_c <- cmpfun(f_opt)