Hacker News new | ask | show | jobs
by enneff 3568 days ago
> Go's "problem" is that it can't efficiently give i a new address in each iteration: it'd have to put each one in a new memory location.

It's not an efficiency issue. How do you think Ruby does it?

1 comments

Then for loops would be linear in space.
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.
Garbage collection is formally defined as an infinite memory simulator[1], so this is not a problem for collected languages.

[1]: https://blogs.msdn.microsoft.com/oldnewthing/20100809-00/?p=...