[R] extremely slow recursion in R?

Jason Liao jg_liao at yahoo.com
Fri Aug 25 15:22:31 CEST 2006


Thank you, Thomas and Joerg! Joerg's example is extremely useful. In
fact I had wanted to compare R with other interpreting language myself.
I heard that Ruby is not fast among scripting languages. I thus believe
that there is room to improve R's recursive function.

Jason
 
--- Joerg van den Hoff <j.van_den_hoff at fz-rossendorf.de> wrote:
> maybe someone's interested:
> I made the same observation of seemingly very slow recursion
> recently: 
> just for fun I used the (in)famously inefficient
> 
> fib <- function(n = 1) {
>     if (n < 2)
>        fn <- 1
>     else
>        fn <- fib(n - 1) + fib(n - 2)
>     fn
> }
> 
> for calculating the fibonacci numbers and compared `fib(30)' (about 
> 1.3e6 recursive function calls ...) to some other languages (times in
> sec):
> 
> language  time
> ==============
> C          0.034  (compiled, using integers)
> Ocaml      0.041  (compiled, using integers)
> Ocaml      0.048  (interpreted, using integers)
> C          0.059  (compiled, using floats)
> Lua        1.1
> ruby       3.4
> R          21
> octave    120
> 
> apart from octave (which seems to have a _real_ issue with recursive 
> function calls), R is by far the slowest in this list and still a
> factor 
> 7-20 slower than the interpreter based Lua and ruby. the speed loss 
> compared to C or Ocaml is about a factor of 350-600 here (Ocaml keeps
> 
> its speed more or less in this simple example even in 'script mode', 
> which is remarkable, I think (and it usually loses only a factor of 
> about 7 or so in script mode compared to the compiled variant)
> 
> for the specialists the bad performance of R in this situation might
> not 
> be surprising, but I was not aware that recursive function calls are 
> seemingly as expensive as explicit loops (where the execution time
> ratio 
> of R to C again is of the same order, i.e. =~ 400).
> 
> of course, such comparsions don't make too much sense: the reason to
> use 
> R will definitely not be its speed (which, luckily, often does not 
> matter), but the combination of flexible language, the number of 
> available libraries and the good 2D graphics.
> 
> 
> 
> joerg
> 


Jason Liao, http://www.geocities.com/jg_liao
Department of Epidemiology and Biostatistics
Drexel University School of Public Health
245 N. 15th Street, Mail Stop 660
Philadelphia, PA 19102-1192
phone 215-762-3934



More information about the R-help mailing list