[swift-users] Why are Swift Loops slow?

Gerriet M. Denkmann g at mdenkmann.de
Wed Oct 12 23:06:28 CDT 2016


> On 12 Oct 2016, at 23:05, Joe Groff via swift-users <swift-users at swift.org> wrote:
> 
>> 
>> On Oct 12, 2016, at 2:25 AM, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
>> 
>> uint64_t nbrBytes = 4e8;
>> uint64_t count = 0;
>> for( uint64_t byteIndex = 0; byteIndex < nbrBytes; byteIndex++ )
>> {
>> 	count += byteIndex;
>> 	if ( ( byteIndex & 0xffffffff ) == 0 ) { count += 1.3; }  (AAA) 
>> };
>> 
>> Takes 260 msec.
>> 
>> Btw.: Without the (AAA) line the whole loop is done in 10 μsec. A really clever compiler!
>> And with “count += 1” instead of “count += 1.3” it takes 410 msec. Very strange. 
>> But this is beside the point here.
>> 
>> 
>> Now Swift:
>> let nbrBytes = 400_000_000
>> var count = 0
>> for byteIndex in 0 ..< nbrBytes
>> {
>> 	count += byteIndex
>> 	if ( ( byteIndex & 0xffffffff ) == 0 ) {count += Int(1.3);}
>> }
>> 
>> takes 390 msec - about 50 % more.
>> 
>> Release build with default options.
> 
> This is a useless benchmark because the loop does no observable work in either language.

I quite agree that this is useless as a benchmark.
It is an abstraction of some real code, which has the common feature that inside the loop is not done anything lengthy.

Following some very helpful remarks from Greg Parker I was able to improve the Swift code by a factor of 3, making it on par with ObjC:
1. using a signed loop counter (factor of 2)
2. using “count = count &+ something” instead of “count += something” (factor of 1.5).

So this exercise gave me some very valuable insights into using Swift (or into some shortcomings of the current Swift compiler).

Thanks again to Greg Parker for his comments and suggestions!

Kind regards,

Gerriet.



More information about the swift-users mailing list