Sorry for my first post being a question. I usually do a quick search and find a solution to anything i need so, never needed an account.
Since I started using Lua I've been led to believe that localizing functions is always faster, but reciently I've been creating some convenience modules and found something strange with the Lua 'iterator' functions when localized.
Some example code:
Code: Select all
local lua_pairs = pairs
local lua_ipairs = ipairs
local lua_next = next
local love_timer = love.timer
local count = 10000000
function love.load()
local tbl1, tbl2 = { }, { }
for i = 1, count do
tbl1["id:" .. i] = i
tbl2[i] = i
end
collectgarbage("collect")
love_timer.sleep(2)
print("\nPAIRS:")
local start1 = love_timer.getTime()
for k,v in lua_pairs(tbl1) do end
print("\tLOCAL:", love_timer.getTime() - start1)
local start2 = love_timer.getTime()
for k,v in pairs(tbl1) do end
print("\tGLOBAL:", love_timer.getTime() - start2)
collectgarbage("collect")
love_timer.sleep(2)
print("\nKEYED NEXT:")
local start3 = love_timer.getTime()
for k,v in lua_next,tbl1 do end
print("\tLOCAL:", love_timer.getTime() - start3)
local start4 = love_timer.getTime()
for k,v in next,tbl1 do end
print("\tGLOBAL:", love_timer.getTime() - start4)
collectgarbage("collect")
love_timer.sleep(2)
print("\nIPAIRS:")
local start5 = love_timer.getTime()
for k,v in lua_ipairs(tbl2) do end
print("\tLOCAL:", love_timer.getTime() - start5)
local start6 = love_timer.getTime()
for k,v in ipairs(tbl2) do end
print("\tGLOBAL:", love_timer.getTime() - start6)
collectgarbage("collect")
love_timer.sleep(2)
print("\nINDEX NEXT:")
local start7 = love_timer.getTime()
for k,v in lua_next,tbl2 do end
print("\tLOCAL:", love_timer.getTime() - start7)
local start8 = love_timer.getTime()
for k,v in next,tbl2 do end
print("\tGLOBAL:", love_timer.getTime() - start8)
collectgarbage("collect")
love_timer.sleep(2)
print("\nINDEX FOR:")
local start9 = love_timer.getTime()
for i = 1, count do local v = tbl2[i] end
print("\tTIME:", love_timer.getTime() - start9)
end
function love.keypressed(key, code)
if key == "escape" then
love.event.quit()
end
end
Code: Select all
PAIRS:
LOCAL: 1.4657853993122
GLOBAL: 0.081412906292826
KEYED NEXT:
LOCAL: 1.4963958139997
GLOBAL: 0.081174023915082
IPAIRS:
LOCAL: 0.039344312623143
GLOBAL: 0.017881943611428
INDEX NEXT:
LOCAL: 0.18253194889985
GLOBAL: 0.032720755320042
INDEX FOR:
TIME: 0.020053090527654
My results with count set to 10k:
Code: Select all
PAIRS:
LOCAL: 0.0020962886046618
GLOBAL: 0.00049156113527715
KEYED NEXT:
LOCAL: 0.0020934783387929
GLOBAL: 0.00048823980614543
IPAIRS:
LOCAL: 0.00019698217511177
GLOBAL: 8.4566883742809e-005
INDEX NEXT:
LOCAL: 0.00079431594349444
GLOBAL: 0.0001573811750859
INDEX FOR:
TIME: 9.9640572443604e-005
Note: I tried a similar test with the 'math' library and there was an obvious advantage to localization. I'm also on some nice meds right now so, i could just be having a Homer Simpson moment.