Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Callbacks vs Coroutines vs Next when parsing 2-d tables in Lua
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
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
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
$ 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.