[R] Performance note: Preallocating helps? and two questions

Kaspar Pflugshaupt pflugshaupt at geobot.umnw.ethz.ch
Wed Nov 1 15:45:39 CET 2000


> AUcap30<-0
> for(i in 1:length(AU))AUcap30[i]<-min(30,AU[i])
> took over an hour on pentium II 300 mhertz (I esc'ed before it finished)
> but
> AUcap30<-AU 
> for(i in 1:length(AU))AUcap30[i]<-min(30,AU[i])
> is very quick (a few seconds)


> Is this performance difference common in r (ie is linux the same way)?


The crucial thing is that in your first example, AUcap30 is set to 0 (one
number), whereas in the second one, it's initialized as a vector of the same
size as AU. So, in the first one, R has to grow the variable for each
iteration of the loop, and in the second, it just fills in an already
existing vector.

I've noticed similar speed differences for this constellation on Linux, or
on S-Plus (Win or Unix). It really pays to initialize objects in the size
you're going to need.


Cheers

Kaspar Pflugshaupt
-- 

Kaspar Pflugshaupt
Geobotanisches Institut
Zuerichbergstr. 38
CH-8044 Zuerich

Tel. ++41 1 632 43 19
Fax  ++41 1 632 12 15

mailto:pflugshaupt at geobot.umnw.ethz.ch
privat:pflugshaupt at mails.ch
http://www.geobot.umnw.ethz.ch

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list