Skip to content

Instantly share code, notes, and snippets.

@iamalbert
Created August 31, 2016 09:11
Show Gist options
  • Save iamalbert/40c2ba9cdbed69620feb5d597f499d47 to your computer and use it in GitHub Desktop.
Save iamalbert/40c2ba9cdbed69620feb5d597f499d47 to your computer and use it in GitHub Desktop.
lua coroutine vs plain loop
require 'sys'
local n = 100000
local seq = {}
for i = 1, n do seq[i] = i end
local bs = 405
local plainLoop = function()
local yield = {}
for i = 1, #seq do
table.insert( yield, seq[i] )
if #yield == bs then
print(#yield)
yield = {}
end
end
if #yield > 0 then
print(#yield)
end
end
local coroutineYield = function()
local yield = {}
for i = 1, #seq do
table.insert( yield, seq[i] )
if #yield == bs then
coroutine.yield(yield)
yield = {}
end
end
if #yield > 0 then
coroutine.yield(yield)
end
end
local coroutineLoop = function()
local iter = coroutine.wrap( coroutineYield )
for r in iter do
print(#r)
end
end
sys.tic()
plainLoop()
local t1 = sys.toc()
sys.tic()
coroutineLoop()
local t2 = sys.toc()
print( "plain loop", t1 )
print( "coroutine", t2 )
--[[
plain loop 0.0047900676727295
coroutine 0.0039558410644531
--]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment