Iterators and performance

132 views
Skip to first unread message

Pierre Durand

unread,
Apr 15, 2026, 3:50:48 PM (2 days ago) Apr 15
to golang-nuts
In this change https://go-review.googlesource.com/c/go/+/745440/10/src/iter/iter.go
I noticed this comment:

// Using the desugared implementations instead of 'range seq' runs
// about 2x faster than the code in the comments based on range loops.
// The cost of range loops comes from the compiler heap-allocating a
// control variable, and additional checks of well-behavedness w.r.t.
// concurrency, panics, stopping when yield returns false, etc.
// There's no value to these "middleware" iterators repeating these
// checks: the user's range loop (the ultimate consumer) will keep
// the underlying iterator 'seq' (the ultimate producer)


This comment confirms what I experimented in my benchmarks:
iterating a sequence with "for ... range ..." is slower and consumes more resources than calling the iterator function.
Is there any plan to improve the compiler regarding this issue ?

tapi...@gmail.com

unread,
Apr 16, 2026, 4:26:08 AM (2 days ago) Apr 16
to golang-nuts
Yes, there are. This is a known problem for a while. https://github.com/golang/go/issues/69015
But I doubt the problem is being addressed now.
They even ignore some more important problems in iterators:
 
Reply all
Reply to author
Forward
0 new messages