For-loop overhead tests

Hi there!

I've been doing some tests for myself and thought I would share the results, just so people know. It's nothing revolutionary or unexpected, but for those looking to squeeze every drop of speed out of their calculations it might be worth it - in short, you can about double the speed of your operations, depending on the complexity, if you do things manually.

Basically I've been comparing the processing overhead of using two nested for-loops to fill a 5x5 array, to filling it in 'manually'.

I've always compared these two methods:

1) two for-loops to fill in a 5x5 Array
for y = 0,4
for x = 1,5
Array[x+y*5] = ... -- code here
end
end

2) 25 single line statements to fill in the Array
Array[1] = ... -- code here
until
Array[25] = ... -- code here

All tests do 100.000 iterations, on an iPhone 3G.

So, the results of the tests:

1) setting Array[..] = 1

with for-loops: 3969 ms
line by line: 1775 ms = more than twice as fast. This is very important for setting arrays to all zero, for example.

2) setting Array[..] = ((12*4*6)+4)*11

with for-loops: 4020 ms
line by line: 1701 ms = more than twice as fast. Weird that these simple calculations are faster or about as fast as just setting to 1. I guess simple math is really fast in Corona/Lua which is good.

3) setting Array[..] = otherArray[1] + otherArray[2]

with for-loops: 8350 ms
line by line: 5650 ms = getting from arrays means taking a speed hit, apparently, but line by line is still more than a quarter faster.

My conclusions:

1) Obviously, setting up for-loops comes at a price, compared to line by line statements. Setting up nested for-loops even more. The choice between either method depends on a lot of factors:
- the number or items to go over: you're not going to do 1000 line by line statements. But 25 or so is feasible.
- how time-critical your code is: in an enterframe loop, it could make sense to do this line by line.

2) The gains you make by doing line by line work, naturally diminish as the complexity of your code per array-item increases: shaving a second off a 3 second loop is great. Shaving a second off a 60 second loop is probably not worth the hassle of line-by-line processing.

There you have it, folks!
Thomas

views:1802 update:2011/10/10 21:27:38
corona forums © 2003-2011