Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop: why is i++ slower than i = i + 1 in swift

that is a normal empty loop with a normal increment operator "i++"

import Foundation

let start = CFAbsoluteTimeGetCurrent()

for var i = 0; i < 1000000; i++ {

}

let timeTaken = CFAbsoluteTimeGetCurrent() - start

println(timeTaken) // 0.0229730010032654

but this loop with "i = i + 1" is much faster

import Foundation

let start = CFAbsoluteTimeGetCurrent()

for var i = 0; i < 1000000; i = i + 1 {

}

let timeTaken = CFAbsoluteTimeGetCurrent() - start
println(timeTaken) // 0.00384700298309326

the second loop is 5x - 6x times faster

i understand swift is still in beta and i don't compare it to other languages but that makes no sense for me

like image 707
David Nadoba Avatar asked Jun 19 '14 09:06

David Nadoba


1 Answers

isnt that a optimizer problem? a fair test world be

var i = 0
for j in 1..1000000 {
i++
}

var i = 0
for j in 1..1000000 {
i = i + 1
}
like image 142
Christian Dietrich Avatar answered Oct 10 '22 05:10

Christian Dietrich