[R] A question on Programming

Duncan Murdoch murdoch.duncan at gmail.com
Thu Nov 10 16:44:56 CET 2011


On 10/11/2011 10:28 AM, R. Michael Weylandt wrote:
> Yes, there will be some reduction in speed:
>
> E.g.,
>
> >  system.time(replicate(1e5, (function() sum(1:10))()))
>     user  system elapsed
>    0.696   0.022   0.729
> >  system.time(replicate(1e5, sum(1:10)))
>     user  system elapsed
>    0.292   0.006   0.306
>
> But it's not much: 3 tenths of a second for 10,000 calls. It's
> certainly worth it for ease of readibility and debugging.

I don't think your test is valid:  you're not just calling the function 
in the upper loop, you're creating it too.  Here's what I see:

First, the version I complained about:

 > system.time(replicate(1e5, (function() sum(1:10))()))
    user  system elapsed
    0.35    0.00    0.35

Now a more realistic one:

 > f <- function() sum(1:10)
 > system.time(replicate(1e5, f()))
    user  system elapsed
    0.25    0.00    0.25

Now the version with no function call:

 > system.time(replicate(1e5, sum(1:10)))
    user  system elapsed
    0.23    0.00    0.24


So creating a function is expensive, but calling one isn't so bad.

Duncan Murdoch



More information about the R-help mailing list