Hacker News new | ask | show | jobs
by settler4 2831 days ago
Doesn't the chained version still iterate over all the elements and squares them before taking the first 3 bigger than 5? the second version only goes over the minimum necessary elements and then breaks. How can the first be higher performance?
1 comments

No, the iterators are "lazy" (pull-based). Both implementations will perform the same amount of work.

Oftentimes the iterator will be faster, though, because the compiler can reason about what you're doing easier with an iterator vs. iterating via manual sequential indexing.