[swift-evolution] [Pitch] Retiring `where` from for-in loops

Brent Royal-Gordon brent at architechies.com
Thu Jun 9 03:29:41 CDT 2016


> I've taken the time to run a test, going through milion numbers (several times) using:
> 
> for i in arr { if i % 2 == 0 { continue } }
> for i in arr where i % 2 == 0 { }
> for i in arr.filter({ $0 % 2 == 0 }) { }
> for i in arr.lazy.filter({ $0 % 2 == 0 }) { }
> 
> Results:
> 
> - plain for loop with if-continue: 27.19 seconds (+1.76%)
> - with where: 26.72 seconds (+0.00%)
> - .filter: 44.73 seconds (+67.40%)
> - .lazy.filter: 31.66 seconds (+18.48%)

This is great data. I have a hard time imagining a little compiler work couldn't make if-continue as fast as for-where, but lazy.filter might be a taller order for it, and optimizing plain filter could actually change behavior.

A month or two ago, I actually fell into the "just use the higher-order functions" camp on this question, but I've been rethinking that more and more lately. Between the trailing closure incompatibility, the need to remember to use `lazy` to get decent performance, and now the noticeable speed difference even *with* lazy, I'm no longer convinced that answer is good enough.

(Though I do think `while` is probably too niche to bother with as a first-class feature, and I am open to if-continue on the `where` clause.)

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list