Re: Faster 'generic for' for raw table

"'Martin Eden' via lua-l" <[email protected]> Fri, 12 Jun 2026 15:53:08 +0200
Newsgroups gmane.comp.lang.lua.general
Message-ID <[email protected]>
On 2026-06-12 13:51, 云风 Cloud Wu wrote:
> 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.
>
My test (based on yours and lhf's recommendation) :

   -- Lua 5.5.0  Copyright (C) 1994-2025 Lua.org, PUC-Rio
   do
     local t = {}
     for i = 1, 100e6 do t[i] = i end

     local tic = os.clock()

     -- ( Test
     -- for i = 1, #t do t[i] = -t[i] end -- 1.41
     -- for i in ipairs(t) do t[i] = -t[i] end -- 2.60
     for i in pairs(t) do t[i] = -t[i] end -- 3.63
     -- )

     local tac = os.clock() - tic

     print(tac)
   end

No surprises for me, I'll still be using ipairs.

And hey, it's hundred millions operations under five seconds!
In my adolescence common-sense estimation was one million per second.

-- Martin

-- 
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/aecedf6e-98eb-4f19-a29d-99b125c9effb%40disroot.org.