Boosting code performance
In the previous section, we demonstrated how to use profiling tools to identify a performance bottleneck in the code. In this section, you will learn about a number of approaches to boosting code performance.
Using built-in functions
Previously, we demonstrated the performance difference between my_cumsum1()
, my_cumsum2()
and the built-in function cumsum()
. Although my_cumsum2()
is faster than my_cumsum1()
, when the input vector contains many numbers, cumsum()
is much faster than them. Also, its performance does not decay significantly even as the input gets longer. If we evaluate cumsum
, we can see that it is a primitive function:
cumsum ## function (x) .Primitive("cumsum")
A primitive function in R is implemented in C/C++/Fortran, compiled to native instructions, and thus, is extremely efficient. Another example is diff()
. Here, we will implement computing vector difference sequence in R:
diff_for <- function(x) { n <- length(x) - 1 res ...