[swift-users] Looping with UInt64

Greg Parker gparker at apple.com
Wed Oct 12 01:25:48 CDT 2016


> On Oct 11, 2016, at 11:04 PM, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
> 
> With:
> let nbrBytes = 400_000_000
> let localArray = UnsafeMutablePointer<UInt8>.allocate(capacity: nbrBytes)
> //	touch every page before summing:
> for i in 0 ..< nbrBytes / 4096 { localArray[ 4096 * i ] = 1 }
> 
> This rather innocent loop:
> var count: UInt64 = 0
> for index in 0 ..< loopLimit { count += UInt64( localArray[ Int(index) ] ) }
> 
> takes 2.4 times as long if preceded by:
> 	let loopLimit = UInt64(nbrBytes)	
> compared to:	
> 	let loopLimit = Int(nbrBytes)	
> 
> Why can’t Swift iterate in UInt64  as efficient as with Int?
> Any real issue here which I am overlooking or just a compiler bug?

Looks like missed optimization opportunities due to the signedness of the index. 

If the index is a signed type (Int, Int32, Int64) then the compiler optimizes away all of the integer overflow checks and performs two operations per loop iteration. 
If the index is unsigned (UInt, UInt32, UInt64) then the compiler doesn't unroll the loop and doesn't remove all of the overflow checks. 
I don't see any reason why the same optimizations would be disallowed in the unsigned case so it's probably a gap in some optimizer pass somewhere.


-- 
Greg Parker     gparker at apple.com <mailto:gparker at apple.com>     Runtime Wrangler


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161011/a4ec321b/attachment.html>


More information about the swift-users mailing list