Lua 5.0 introduced generic for/pairs to replace Lua 4.0's direct
iteration of raw tables. While generic for is very powerful, there's a
small issue - it's somewhat slower because a function call is required
for each iteration.
I hope Lua can continue providing a direct way to iterate raw tables,
such as maintaining Lua 4.0's behavior when the first parameter of
generic for is 'nil' by iterating the second table object.
I wrote a small piece of code to conduct a comparative test between
Lua 5.5 and a minor patch I implemented in Lua 5.5 (Using lua_next
replaced ProtectNT(luaD_call(L, ra + 3, GETARG_C(i))); /* do the call
*/ in the case OP_TFORCALL)
local t = {}
for i = 1, 100000000 do
t[i] = i
end
local ti = os.clock()
for k in pairs(t) do
end
ti = os.clock() - ti
print(ti)
The original lua 5.5 cost 0.97s , and patched version (using lua_next
instead of luaD_call) cost 0.42s . It's almost twice as fast.
Considering that most scenarios involve iterating raw tables, I
believe this optimization is meaningful.
--
http://blog.codingnow.com