Skip to content
Prev 256848 / 398506 Next

for loop performance

On 04/13/2011 02:55 PM, Barth B. Riley wrote:
Hi Barth

The 'it gets slower' symptom is often due to repeatedly 'growing by 1' a 
list or  other data structure, e.g.,

   m = matrix(100000, 100)
   n = 20000
   result = list()
   system.time(for (i in seq_len(n)) result[[i]] = m)

versus 'pre-allocate and fill'

    result = vector("list", n)
    system.time(for (i in seq_len(n)) result[[i]] = m)

The former causes 'result' to be copied on each new assignment, and the 
size of the copy gets larger each time.