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

L. Mihalkovic laurent.mihalkovic at gmail.com
Thu Jun 9 05:56:03 CDT 2016


> On Jun 9, 2016, at 12:27 PM, Charlie Monroe via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>>> On Jun 9, 2016, at 10:29 AM, Brent Royal-Gordon <brent at architechies.com> wrote:
>>> 
>>> 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.
> 
> There will IMHO always be noticeable overhead since you're calling a function which is then invoking a closure. When you look at what that means:
> 
> - thunks generated around the invocation, which are a few instructions
> - new stack frame for each call (correct me if I'm wrong). 
> 
> So instead of a single `i % 2 == 0` (which is just 2-3 instructions, depending on the architecture and optimization settings), it will invoke the closure milion times, if the array contains a milion members.
> 
> Maybe I'm over-optimizing, but 18% seemed like a lot to me.

It looks like this should not be fate, and a pattern that could end up generating the same code after proper inlining.

> 
> 
>> 
>> (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
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


More information about the swift-evolution mailing list