Faster 'generic for' for raw table
云风 Cloud Wu <[email protected]> Fri, 12 Jun 2026 19:51:42 +0800
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAJnYMr1V547AwTBnURckKDNbMmO85_L9WLZ28SiGK46kiUxfgQ@mail.gmail.com> |
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
--
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion visit https://groups.google.com/d/msgid/lua-l/CAJnYMr1V547AwTBnURckKDNbMmO85_L9WLZ28SiGK46kiUxfgQ%40mail.gmail.com.