View Single Post
03-16-12, 11:39 AM   #8
Mikord
A Theradrim Guardian
AddOn Author - Click to view addons
Join Date: Jul 2006
Posts: 61
Originally Posted by Animor View Post
Why is it faster to avoid ipairs and simply iterate through the array, as you wrote?
The simplest answer is that ipairs has overhead associated with it since it is an iterator function. The example using the # operator, on the other hand is, just looping from 1 to the number of elements in the array.


Here are some very basic benchmark results between an empty loop iterating over an array with 10,000,000 entries using ipairs versus the # operator. The code is at the bottom of the post:

Code:
Generating array with 10000000 entries...
Iterating through 10000000 entries with # operator...
elapsed time: 0.09
Iterating through 10000000 entries with ipairs...
elapsed time: 1.34

Lua Code:
  1. local NUM_ITERATIONS = 10000000
  2.  
  3. print(string.format("Generating array with %d entries...", NUM_ITERATIONS))
  4. local array = {}
  5. for i = 1, NUM_ITERATIONS do
  6.     array[i] = i
  7. end
  8.  
  9. print(string.format("Iterating through %d entries with # operator...", #array))
  10. local start = os.clock()
  11. for i = 1, #array do
  12. end
  13. print(string.format("elapsed time: %.2f", os.clock() - start))
  14.  
  15. print(string.format("Iterating through %d entries with ipairs...", #array))
  16. local start = os.clock()
  17. for k, v in ipairs(array) do
  18. end
  19. print(string.format("elapsed time: %.2f", os.clock() - start))

Last edited by Mikord : 03-16-12 at 11:43 AM.
  Reply With Quote