Re:One Billion Nested Loop Iterations
by MooseBurger on Tuesday November 26, 2024 @03:56PM
(#42249995)
I disagree w.r.t. python. You shouldn't need a numerical computing library to do a for loop generally.
Kick the habit. For loops are what "goto" was 20 years ago. Error prone and not possible to abstract for example for parallel execution.
I think the comparison to goto is a little extreme, but actually not too crazy. I could see a future where the accepted best practice is to use parallelized operations for everything, and only use sequential loops in cases where the underlying concept is inherently sequential (gradient descent, iterative hashing, etc.).
If you write the R code using vectorised operations it’s significant orders of magnitude faster (148 seconds to 1.5 milliseconds on posit.cloud).
The nested loop becomes: j <- sum((seq_len(100000) - 1) %% u) a <- a + j + r
Just think twice before using a for loop. Most of the time it is not needed.