Speed comparison : ipairs vs pairs vs numerical loop [benchmark]

I didn’t think this would fit anywhere else so I just put this here.

The purpose of this is to share as information,
the average of the time taken by various loops to execute and print a value, regardless of being numeric or generic from a numerically indexed table.

Note: The criteria is is no way perfect or the correct method, but gives insight on how long different generators could take to return a value. Also, pairs is not being used for it’s intended purpose (that is iterating through dictionaries) so the results are further not well founded.

There is also negligible difference in the time each loop takes, but preferably use each loop where necessary.

Testing Criteria
list = {}

for i = 1, 100 do
    table.insert(list,"object"..i)
end

local x = 0
local sum = 0




--Test 1, let's see how long it takes to iterate using a numeric loop


repeat -- the experiment 50 times and take an average

    x = x+1
    local t = tick()

    for i = 1, #list do
        print(list[i])
    end

    sum = sum + ((tick()-t)*10^6 )

until x == 50

print("average:"..sum/50 .. "ms")





-- average over 50 times was : 68744.8 ms
-- the average over 200 times was 74358 ms (to 1 decimal place)


-- Test 2, ipairs (fastest generator)

repeat

    x = x+1
    t = tick()

    for _, val in ipairs(list) do
        print(val)
    end

    sum = sum +(((tick()-t)*10^6 ))

until x == 50

print(sum/50)

-- the average over 50 times was 55565.7 ms (to 1 decimal place)


-- pairs

repeat

    x = x+1
    t = tick()

    for _, val in pairs(list) do
        print(val)
    end

    sum = sum +(((tick()-t)*10^6 ))

until x == 50

print(sum/50)
     

-- average over 50 times was 63237.1 ms (to 1 decimal place)

Result :

All values are taken over an average of 50 times (this should’ve been much larger), rounded to one decimal place.

Time taken to execute/ in increasing order

ipairs : 55565.7 ms
pairs : 63237.1 ms
numerical for loop : 68744.8 ms / 74358 ms taken over 200 times

A very old benchmark from 2013, next faster than table[i]

I recently learnt that ipairs is only this fast with our custom Lua interpreter, Luau; in Vanilla Lua it is slower than pairs.

Also CrazyMan32 wrote this one, check it out:
Battle of the loops

26 Likes