Skip to content

Instantly share code, notes, and snippets.

@zwim
Created October 24, 2022 19:52
Show Gist options
  • Save zwim/370ddbcee2d0841cbfe095e3f4b3dfdf to your computer and use it in GitHub Desktop.
Save zwim/370ddbcee2d0841cbfe095e3f4b3dfdf to your computer and use it in GitHub Desktop.
LUAJIT Comparison of pairs, ipairs and indexing
#!/usr/bin/env luajit
--[[
Adapted from https://gist.github.com/dpino/647b9d2e12aa8ff859b4
Environment: Lenovo ThinkPad T520 / 16GB RAM / i7-3740QM CPU @ 2.70GHz
| pairs | ipairs | indexing |
| 1.000000 | 4.283464 | 4.058733 |
| 0.233456 | 1.000000 | 0.947535 |
| 0.246382 | 1.055370 | 1.000000 |
]]--
local ITERATIONS = 1000000
local x
local function array(n)
local result = {}
for i=1, n do
table.insert(result, tostring(i))
end
return result
end
local function execute_times(f, times)
local a = array(100)
local begin = os.clock()
for i=1,times do
f(a)
end
local finish = os.clock()
return finish - begin
end
local times = {}
-- Pairs
local elapse_time1 = execute_times(function(a)
for j,v in pairs(a) do
x=v
end
end, ITERATIONS)
times["pairs"] = elapse_time1
-- iPairs
local elapse_time2 = execute_times(function(a)
for _,v in ipairs(a) do
x=v
end
end, ITERATIONS)
times["ipairs"] = elapse_time2
-- Indexing
local elapse_time3 = execute_times(function(a)
local len = #a
for j=1,len do
x=a[j]
end
end, ITERATIONS)
times["indexing"] = elapse_time3
local results = {
{ times["pairs"]/times["pairs"], times["pairs"]/times["ipairs"], times["pairs"]/times["indexing"] },
{ times["ipairs"]/times["pairs"], times["ipairs"]/times["ipairs"], times["ipairs"]/times["indexing"] },
{ times["indexing"]/times["pairs"], times["indexing"]/times["ipairs"], times["indexing"]/times["indexing"] },
}
print("| pairs | ipairs | indexing |")
for _, row in ipairs(results) do
io.write(string.format("| %.6f ", row[1]))
io.write(string.format("| %.6f |", row[2]))
io.write(string.format(" %.6f |", row[3]))
io.write("\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment