Skip to content
Prev 202032 / 398503 Next

Iteration idioms & laziness

On 27/11/2009 3:36 PM, Alexander S?ndergaard wrote:
I believe the iterators and foreach packages give ways to iterate 
without creating the whole array, so they might do what you want.  But 
is the allocation really a problem on modern computers?  The for loop 
version of your example, i.e.

total <- 0
for (i in seq(1,1e6)) total <- total + i
total

uses about 4 megabytes of memory, not "gigabytes".  If you increase the 
limit from 1e6 to 1e9 you'll get gigabytes, but it'll probably take tens 
of minutes to finish running on a system that can run it:  the big 
problem is the interpreted looping, not the memory use.

R has always followed the strategy of making it easy to jump out to C 
code when speed matters, so the natural idiom for your problem is to use 
sum(), not to program it yourself.  In more complicated examples, or if 
you really do want to sum the integers from 1 to a billion on a system 
with limited memory, you'll have to write the C yourself, but it's not hard.

Duncan Murdoch