[swift-evolution] [Proposal] Change guarantee for GeneratorType.next() to always return nil past end

Dave Abrahams dabrahams at apple.com
Mon Mar 7 08:19:54 CST 2016


on Sun Mar 06 2016, Patrick Pijnappel <swift-evolution at swift.org> wrote:

> My intuition says the extra state & branch needed for generators like
> TakeWhile could very well be optimized away in most cases if you dont
> make use of its post-nil behavior. Say TakeWhile is implemented as such:
>
> if done { return nil }
> guard let element = base.next() where predicate(element) else {
>   done = true
>   return nil
> }
> return element
>
> If the generator is then used in the common case:
>
> let generator = TakeWhileGenerator(...)
> while let element = generator.next() {
>   foo(element)
> }
>
> Should give us effectively:
>
> var base = ...
> let predicate = ...
> var done = false
> while true {
>   if done { break }
>   guard let element = base.next() where predicate(element) else {
>     done = true
>     break
>   }
>   foo(element)
> }
>
> The optimizer should see (or at least could see) `done` is never read after
> it's written to (thus removing the assignment), and therefore
> when checking the condition it can only be false (thus it can also be
> removed).

That's a good point.  Kevin, what do you think?

-- 
-Dave



More information about the swift-evolution mailing list