lua-users home
lua-l archive

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



On 29/09/2006, at 1:00 PM, Glenn Maynard wrote:

# echo 'for i = 1,1000000 do local a = { 5, 6, 7, 8, 8 }; a = {}; end' | time lua - 1.75user 0.00system 0:01.76elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k

# echo 'for i = 1,1000000 do local a = { 5, 6, 7, 8, 8 }; for k in pairs(a) do a[k] = nil; end; end' | time lua - 4.98user 0.00system 0:05.00elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k

It's hard to imagine the latter being faster.  It's slower even with
even just one element.

Your test is actually making my suggestion do both things:

a = { 5, 6, 7, 8, 8 }  --> create a new table, assign to a
for k in pairs(a) do a[k] = nil; end;  --> delete each element

If you move the table creation outside the loop, so that the table is genuinely being reused, then it is faster to delete elements for a small number:

local a = {}
for i = 1, 3000000 do
  a [1] = 5
  a [2] = 6
  a [3] = 7
  a [4] = 8
  for k in ipairs (a) do
    a [k] = nil
  end -- for
end -- loop

real    0m14.943s
user    0m14.930s
sys     0m0.010s



And using the "make a new table" method:

local a = {}
for i = 1, 3000000 do
  a [1] = 5
  a [2] = 6
  a [3] = 7
  a [4] = 8
  a = {}
end -- loop

real    0m15.659s
user    0m15.650s
sys     0m0.000s


I was about to write that the break-even point is around 4 elements, however some further testing shows that adding more elements makes both tests take longer, with the "set all to nil" keeping slightly ahead of "make a new table". I am presuming that creating 3000000 tables (with resulting memory allocations) takes a significant time. It is probably giving the garbage-collector some work to do.

I finally found that at 7 elements the "make a new table" method took 0.4 seconds less for 3000000 iterations, and 3 seconds less for 8 elements.

I admit that making a new table is cleaner, other things being equal. :)

- Nick