[R] speeding up a recursive function
Gabor Grothendieck
ggrothendieck at gmail.com
Sun Apr 2 19:03:17 CEST 2006
On 4/2/06, Prof Brian Ripley <ripley at stats.ox.ac.uk> wrote:
> On Sun, 2 Apr 2006, Federico Calboli wrote:
>
> > is there any general advice about speeding up recursive functions
> > (not mentioning 'don't use them')?
>
> Well, that's very general (did you mean recursive functions in R or C or
> what?). Recursion is not particularly slow in R, and you are limited to a
> depth of a most a few thousand. E.g.:
>
> > f <- function(x) if(x > 0) f(x-1)
> > system.time(for(i in 1:100) f(2000))
> [1] 0.59 0.00 0.60 NA NA
>
> which is 3 usec per call.
>
> One piece of advice is to keep memory usage down, as in many of the
> examples I have looked at the speed issue was actually a memory issue,
> with datasets being copied at each level.
Some functional languages have a feature called tail recursion that
can provide performance improvements if you write your recursions
to take advantage of it:
http://en.wikipedia.org/wiki/Tail_recursion
but I don't think R supports it. Is this likely to become available
in R?
More information about the R-help
mailing list