Re: Faster 'generic for' for raw table
云风 Cloud Wu <[email protected]> Fri, 12 Jun 2026 20:53:39 +0800
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAJnYMr0U8WsTV9f-m1XnTCcOXoE_AWDuxe1m48cjUpwBLM0Niw@mail.gmail.com> |
云风 Cloud Wu <[email protected]> 于2026年6月12日周五 20:42写道: > a minor optimization would be valuable. In many cases, Lua's function > calls are still relatively slow. When optimizing performance hotspots, > we can use code generators to inline function calls into flat code. > However, iterating raw tables remains unavoidable. If the language > itself could provide a way to iterate raw tables, it would be very > useful If we want to avoid calling pairs/next, storing the raw table's keys in a sequence (like a list) can often double the speed. For example, consider this code local t = {} for i = 1, 100000000 do t[i] = i end local ti = os.clock() local sum = 0 for k,v in pairs(t) do sum = sum + v end ti = os.clock() - ti print(ti, sum) If we cache the keys into a sequence table first : local keys = {} local i = 1 for k in pairs(t) do keys[i] = k i = i + 1 end And then use numerical for loop instead, It also has twice the performance. local ti = os.clock() local sum = 0 for i = 1, #keys do sum = sum + t[keys[i]] end ti = os.clock() - ti print(ti, sum) -- 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/CAJnYMr0U8WsTV9f-m1XnTCcOXoE_AWDuxe1m48cjUpwBLM0Niw%40mail.gmail.com.