lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Just a little note for micro-optimizers:

In Lua 5, tables are implemented as having two parts: an array part, consisting of integer-keyed values, and a general hash table part. A key is a candidate for the array part if the array part is mostly consecutive. (This way assigning to t[20000] will not allocate a 20000 element array part, unless t[1]...t[19999] is already mostly used.)

The array part seems much faster.

I had an event queue that looked like this:

  {next=3, n=4, nil, nil, {...}, {...}}

As each event was consumed, I nil'd out the old event from the table. When I ran out of events, I'd just table.insert more on the end. So eventually, the table would look like:

  {next=20000, n=20001, [20000]={...}, [20001]={...}}

which I think was entirely stored as a hash table.

I changed my "get more events" strategy to reset t.n and t.next to near 0 when I went to get more, thus keeping the events in the array part of the table. This sped up my *whole* *program* by 3-5%.

Also, if you plan on doing a lot of unpack() calls on prepared tables you construct, add an "n=3" to your {"start", "b", {}, n=3} tables. That was good for another 5% speedup....

Jay