3## this short example was provided in response to this StackOverflow questions:
4## http://stackoverflow.com/questions/6807068/why-is-my-recursive-function-so-slow-in-r
5## and illustrates that recursive function calls are a) really expensive in R and b) not
6## all expensive in C++ (my machine sees a 700-fold speed increase) and c) the byte
7## compiler in R does not help here.
9suppressMessages(library(Rcpp))
14## A C++ version compile with cppFunction
15fibRcpp <- cppFunction( '
16int fibonacci(const int x) {
17 if (x == 0) return(0);
18 if (x == 1) return(1);
19 return (fibonacci(x - 1)) + fibonacci(x - 2);
24## for comparison, the original (but repaired with 0/1 offsets)
25fibR <- function(seq) {
26 if (seq == 0) return(0);
27 if (seq == 1) return(1);
28 return (fibR(seq - 1) + fibR(seq - 2));
31## also use byte-compiled R function
34## load rbenchmark to compare
37N <- 35 ## same parameter as original post
38res <- benchmark(fibR(N),
41 columns=c("test", "replications", "elapsed",
42 "relative", "user.self", "sys.self"),
45print(res) ## show result