public
Created

Callbacks vs Coroutines vs Next when parsing 2-d tables in Lua

  • Download Gist
Results
1 2 3 4 5 6 7 8
$ time lua callbacks.lua
lua callbacks.lua 0.52s user 0.00s system 97% cpu 0.534 total
 
$ time lua coroutines.lua
lua coroutines.lua 1.12s user 0.00s system 99% cpu 1.123 total
 
$ time lua next.lua
lua next.lua 1.35s user 0.00s system 99% cpu 1.358 total
callbacks.lua
Lua
1 2 3 4 5 6 7 8 9 10 11 12 13
root = { {a=1,b=2,c=3}, {d=4,e=5,f=6}, {g=7,h=8,i=9} }
 
function eachGrandChild(callback)
for _,child in pairs(root) do
for index,grandChild in pairs(child) do
callback(index, grandChild)
end
end
end
 
for i=1, 200000 do
eachGrandChild(function(index, grandChild) end)
end
coroutines.lua
Lua
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
root = { {a=1,b=2,c=3}, {d=4,e=5,f=6}, {g=7,h=8,i=9} }
 
function eachGrandChild()
for _,child in pairs(root) do
for index,grandChild in pairs(child) do
coroutine.yield(index, grandChild)
end
end
end
 
function grandChildren()
return coroutine.wrap(eachGrandChild)
end
 
for i=1, 200000 do
for key, val in grandChildren() do
end
end
next.lua
Lua
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
root = { {a=1,b=2,c=3}, {d=4,e=5,f=6}, {g=7,h=8,i=9} }
 
function eachGrandChild(state)
while state.childIndex ~= nil do
local child = root[state.childIndex]
state.grandChildIndex = next(child, state.grandChildIndex)
if state.grandChildIndex == nil then
state.childIndex = next(root, state.childIndex)
else
return state.grandChildIndex, child[state.grandChildIndex]
end
end
end
 
function grandChildren(root)
return eachGrandChild, {childIndex = next(root)}
end
 
for i=1, 200000 do
for key, val in grandChildren(root) do
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.