<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><br class=""><div><blockquote type="cite" class=""><div class="">On Oct 11, 2016, at 11:04 PM, Gerriet M. Denkmann via swift-users &lt;<a href="mailto:swift-users@swift.org" class="">swift-users@swift.org</a>&gt; wrote:</div><br class="Apple-interchange-newline"><div class=""><div class="">With:<br class="">let nbrBytes = 400_000_000<br class="">let localArray = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: nbrBytes)<br class="">//<span class="Apple-tab-span" style="white-space:pre">        </span>touch every page before summing:<br class="">for i in 0 ..&lt; nbrBytes / 4096 { localArray[ 4096 * i ] = 1 }<br class=""><br class="">This rather innocent loop:<br class="">var count: UInt64 = 0<br class="">for index in 0 ..&lt; loopLimit { count += UInt64( localArray[ Int(index) ] ) }<br class=""><br class="">takes 2.4 times as long if preceded by:<br class=""><span class="Apple-tab-span" style="white-space:pre">        </span>let loopLimit = UInt64(nbrBytes)<span class="Apple-tab-span" style="white-space:pre">        </span><br class="">compared to:<span class="Apple-tab-span" style="white-space:pre">        </span><br class=""><span class="Apple-tab-span" style="white-space:pre">        </span>let loopLimit = Int(nbrBytes)<span class="Apple-tab-span" style="white-space:pre">        </span><br class=""><br class="">Why can’t Swift iterate in UInt64 &nbsp;as efficient as with Int?<br class="">Any real issue here which I am overlooking or just a compiler bug?</div></div></blockquote><br class=""></div><div>Looks like missed optimization opportunities due to the signedness of the index.&nbsp;</div><div><br class=""></div><div>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.&nbsp;</div><div>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.&nbsp;</div><div>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.</div><div><br class=""></div><div><br class=""></div><div>--&nbsp;</div><div>Greg Parker &nbsp; &nbsp; <a href="mailto:gparker@apple.com" class="">gparker@apple.com</a>&nbsp; &nbsp; &nbsp;Runtime Wrangler</div><div><br class=""></div><div><br class=""></div></body></html>