Swift for loops exhibit poor performance

Originator:kamikaze.mark
Number:rdar://17168985 Date Originated:2014-06-04
Status:Open Resolved:
Product:OS X SDK Product Version:Xcode 6 beta
Classification:Performance Reproducible:Always
 
// relative timing of loops in Swift REPL

import Cocoa

func timetask(task: () -> ()) -> Double {
	let t1 = CFAbsoluteTimeGetCurrent()
	task()
	let t2 = CFAbsoluteTimeGetCurrent()
	println("Took \(t2-t1) s")
	return Double(t2-t1)
}

timetask { for var i = 0; i < 1000000; ++i { } }
// Took 0.0195080041885376 s

timetask { for var i = 0; i < 1000000; i += 1 { } }
// Took 0.0038759708404541 s

timetask { var i = 0; for i in 0..1000000 { } }
// Took 3.78008300065994 s

Summary:
for..in with a range takes 1260x longer than an Int loop using += 1. The equivalent Objective-C looping through an NSRange would be nearly as fast as an int loop.

Related: ++i is 6.5x slower than i += 1.

Unrelated: The syntax `for var i in 0..1000000` does not work, but `for var i = 0; i < 1000000; i += 1` does.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!