[swift-evolution] Improvement proposal: change overflow behavior in successor()/predecessor() methods for Int types

Dave Abrahams dabrahams at apple.com
Mon Apr 25 16:53:15 CDT 2016


on Sat Apr 23 2016, Haravikk <swift-evolution at swift.org> wrote:

>     On 7 Apr 2016, at 18:54, Dmitri Gribenko via swift-evolution
>     <swift-evolution at swift.org> wrote:
>
>     On Thu, Apr 7, 2016 at 12:20 AM, Vladimir.S via swift-evolution
>     <swift-evolution at swift.org> wrote:
>
>     But. .successor() .predecessor() methods for Int values do not follow these
>         rules for overflow situations. I.e. :
>         let i : Int8 = Int8.max
>         let k : Int8 = i.successor()
>         - is OK for current Swift compiler. We have i==127 and k==-128, no
>         run-time
>         error.
>
>     This was done for performance reasons. Array's indices are Ints, and
>     adding an overflow check here was causing significant performance
>     issues when iterating over arrays.
>
> Sorry to bump this after it’s been idle for a little while, but I was thinking
> about this again recently and I can’t come up with a test that verifies a
> meaningful performance difference. I just threw the following into a playground:
>
> import Foundation
>
> do {
> let startTime = NSDate().timeIntervalSince1970
> var i = 0
> while i < 1000000 { i = i &+ 1 }
> let elapsed = NSDate().timeIntervalSince1970 - startTime
> }
>
> do {
> let startTime = NSDate().timeIntervalSince1970
> var i = 0
> while i < 1000000 { i = i + 1 }
> let elapsed = NSDate().timeIntervalSince1970 - startTime
> }
>
> My results come out with no discernible performance difference; 

I wouldn't be surprised if these examples compiled down to exactly the
same code because the compiler can hoist the overflow checks out of the
loop.  Try doing the same thing with a sort or a binary search if you
want to experience the difference

> I suspect that this a side-effect of the iteration and storing
> overhead, but it seems to me that this is the kind of minimum
> boilerplate you are going to have anyway if you’re using
> .successor(). I know the issue is specifically with array iteration,
> but I don’t believe I actually need an array involved to demonstrate
> this, in fact the extra overhead would make the difference even less
> noticeable.
>
> Is there a test that can demonstrate a more extreme difference? Even so, if the
> issue is with array iteration then it seems that the best place to fix that is
> in the array’s generator, rather than using the more generic IndexingGenerator
> that has no awareness of the underlying index type.
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-- 
Dave



More information about the swift-evolution mailing list