Skip to content

Instantly share code, notes, and snippets.

@geoffleyland
Created June 13, 2012 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffleyland/2927017 to your computer and use it in GitHub Desktop.
Save geoffleyland/2927017 to your computer and use it in GitHub Desktop.
Lua ipairs and numeric for test
-- Changing TABLE_SIZE didn't seem to change much
local TABLE_SIZE = 10000
local ITERATIONS = (jit and 100000000 or 10000000) / TABLE_SIZE
local a = {}
for i = 1, TABLE_SIZE do
a[i] = i * i
end
local sum, start
-- It's possible that the order in which these for tests are executed could
-- tickle LuaJIT to make one or other faster. I fiddled a bit, but didn't learn
-- anything.
sum = 0
start = os.clock()
for i = 1, ITERATIONS do
local j = 1
while true do
local v = a[j]
if not v then break end
sum = sum + j + v
j = j + 1
end
end
io.stderr:write("while: ", os.clock() - start, "s, ", sum, "\n")
sum = 0
start = os.clock()
for i = 1, ITERATIONS do
for j, v in ipairs(a) do
sum = sum + j + v
end
end
io.stderr:write("ipairs: ", os.clock() - start, "s, ", sum, "\n")
sum = 0
start = os.clock()
for i = 1, ITERATIONS do
for j = 1, TABLE_SIZE do
sum = sum + j + a[j]
end
end
io.stderr:write("fixed-length numeric_for: ", os.clock() - start, "s, ", sum, "\n")
sum = 0
start = os.clock()
for i = 1, ITERATIONS do
for j = 1, #a do
sum = sum + j + a[j]
end
end
io.stderr:write("numeric_for and #: ", os.clock() - start, "s, ", sum, "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment