lua-users home
lua-l archive

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


On Tue, Nov 24, 2020 at 6:46 PM Norman Ramsey wrote:
why wouldn't you simply allocate a fresh table?
Why try to reuse an old one?

The reusing is significantly faster:

local game_field = {}
local game_size = 1000000

local function reuse_old()
   for j = 1, game_size do
      game_field[j] = "white"
   end
   for j = 1 + game_size, 2*game_size do
      game_field[j] = nil
   end
   for j = 1 + 2*game_size, 3*game_size do
      game_field[j] = "black"
   end
end

local function create_new()
   game_field = {}
   for j = 1, game_size do
      game_field[j] = "white"
   end
   for j = 1 + 2*game_size, 3*game_size do
      game_field[j] = "black"
   end
end

local t = os.clock()
for i = 1, 100 do
   reuse_old()
end
print(os.clock() - t)   --> 6.874127

local t = os.clock()
for i = 1, 100 do
   create_new()
end
print(os.clock() - t)   --> 36.050187