2 ms·
I have not looked at Go's iterator range loop implementation yet. So somebody tell me if I'm wrong here. My guess is that Go is probably wrapping the body of t
by atomic128 2y ago
I have not looked at Go's iterator range loop implementation yet. So somebody tell me if I'm wrong here.
My guess is that Go is probably wrapping the body of the range loop into a closure, and passing that closure into the iterator function as the yield function. A break in the body of the loop becomes a "return false" in the closure.
The allocation is probably the closure environment struct (giving access to variables prior to the range loop).
This closure might escape through the iterator function so Go can't just put the environment struct onto the stack, it has to escape to the heap.
The cost is small but it's not free. Usually, not having to think about the allocation is an advantage. In the rare case can't afford the iterator, do it differently.
Go is great.