|
|
|
|
|
by parenthephobia
3567 days ago
|
|
The block inside the loop must be kept in memory whilst there are still anonymous functions which reference the per-iteration loop variables. Loops are linear in space if such functions are being generated and retained in each iteration. If they don't, then iteration stack frames are cleaned up by GC. This applies to each-style loops. Actual Ruby for loops don't have this behaviour. a = []
for i in 1..100
a << ->{ puts i } # append, to a, a function that prints 'i'
end
a[0].call()
This prints 100, since the scope of i covers the entire loop, and not each iteration. They are, however, much faster than each-style loops, since they don't have to make a stack frame for each iteration. |
|