Taking an example like t={1,2,3,4,5}
. Let’s say I have 3 methods to print the elements: all(), pairs(), cor_all(). What is the best way to go about determining the best method to use? I tried looking at the memory usage(negligible). I tried the dt and 'avgDt" i.e. (ttl_dt/event.frame) a ratio u want to stay under 1. My understanding is dt is showing how well the code runs per my machine. If I run the code 1000 times in a frame I can balloon the value and see which one gives a lower avgDt… even then though the numbers weren’t different or consistent enough to really get an idea of a difference though.
local function all(t) local i = 0; local n = #t
return function ()
i = i + 1
if i <= n then return t[i] end
end end
local function cor_all(tbl)
return coroutine.wrap(function()
for i=1,#tbl do
coroutine.yield(tbl[i])
end
end) end
local dt,ttl_dt,last_ms,mspf=0,0,0,1000/display.fps; local function info(event) local stage=display.getCurrentStage(); dt = event.time - last_ms; last_ms = event.time; --[[if dt>20 then dt=20 end]] dt = dt/mspf; ttl_dt=ttl_dt+dt
if event.frame%100==0 then
print(event.frame," |avgDt:"..(ttl_dt/event.frame)) --ttl_dt as a whole value should always be less than event.frame aka ratio under 1
end end
Runtime:addEventListener("enterFrame", function(event)info(event)
local t={1,2,3,4,5}
for i=1,20000 do --frame 500: .93 on its own
-- for obj in all(t) do end --frame 500: 1.17
-- for obj in cor_all(t) do end --frame 500: 2.37
-- for _,v in pairs(t) do end --frame 500: .96
end
end)
I ballooned it to 20,000 iterations and more sensible differences appeared. So is this method valid? It’s about what I would expect honestly. If all() was built-in to the engine like pairs it would run faster than pairs I would assume…coroutines always slow so that checks out. I don’t need more links to optimization guides, I need to actually see the differences at some point. If you balloon to 60k iterations it shows for i=1,#t do end runs ~30% faster than pairs(), which confirms the docs saying pairs is slower.