Skip to content

Instantly share code, notes, and snippets.

@dpino
Last active October 24, 2022 19:32
Show Gist options
  • Save dpino/647b9d2e12aa8ff859b4 to your computer and use it in GitHub Desktop.
Save dpino/647b9d2e12aa8ff859b4 to your computer and use it in GitHub Desktop.
Measures performance of loops iterating with pairs, ipairs and indexing
#!/usr/bin/env luajit
--[[
Environment: Lenovo ThinkPad X200 / 16GB RAM / iCore7 2620M (2.70GHz, 4MB Cache)
| pairs | ipairs | indexing |
| 1.000000 | 5.244480 | 9.388388 |
| 0.190677 | 1.000000 | 1.790146 |
| 0.106515 | 0.558614 | 1.000000 |
]]--
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 = {}
local ITERATIONS = 1000000
-- Pairs
local elapse_time = execute_times(function(a)
for j,v in pairs(a) do
x=v
end
end, ITERATIONS)
times["pairs"] = elapse_time
-- iPairs
local elapse_time = execute_times(function(a)
for _,v in ipairs(a) do
x=v
end
end, ITERATIONS)
times["ipairs"] = elapse_time
-- Indexing
local elapse_time = execute_times(function(a)
for j=1,#a do
x=v
end
end, ITERATIONS)
times["indexing"] = elapse_time
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
@zwim
Copy link

zwim commented Oct 24, 2022

Line 54 should be x=a[j] then the results will change to

|  pairs   |  ipairs  | indexing |
| 1.000000 | 3.133077 | 2.923984 |
| 0.319175 | 1.000000 | 0.933263 |
| 0.341999 | 1.071509 | 1.000000 |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment