Skip to content
Prev 32576 / 398530 Next

Slow computation in for loop

Yves Brostaux <brostaux.y at fsagx.ac.be> writes:
The problem with pseudocode: You didn't really overwrite the "result"
every time did you? I bet you stored it somewhere.

Two common causes of inefficiency are (a) that the stored objects may
be large and (b) some naive ways of storing the results involve
copying all preceding results, e.g.

list.of.results <- list()
for (.....){
     result <- ...
     list.of.results <- c(list.of.results, result)
}

The fix for (a) is to extract what you need and discard the rest
and for (b) to allocate the list up front with the proper length and
assign to list.of.results[[i]].