Originally Posted by Animor
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:
local NUM_ITERATIONS = 10000000
print(string.format("Generating array with %d entries...", NUM_ITERATIONS))
local array = {}
for i = 1, NUM_ITERATIONS do
array[i] = i
end
print(string.format("Iterating through %d entries with # operator...", #array))
local start = os.clock()
for i = 1, #array do
end
print(string.format("elapsed time: %.2f", os.clock() - start))
print(string.format("Iterating through %d entries with ipairs...", #array))
local start = os.clock()
for k, v in ipairs(array) do
end
print(string.format("elapsed time: %.2f", os.clock() - start))