lua-users home
lua-l archive

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


On Mon, Nov 23, 2020 at 3:26 PM Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> Do we have a slender hope that the performance penalty on assigning nils will eventually be fixed?

It seems to me that the issue, if any, is creating new entries in a
table, not assigning nils. I don't expect any penalty when clearing
existing fields.

Following up after classes are over for the day.

The script in the original post has this time for starting at 1 (rerun just a few minutes ago):

$ time lua test.lua 1
Array indices start with 1

real 0m0.147s
user 0m0.130s
sys 0m0.012s

(I did not rerun the starting-at-0 case because I did not have the patience to wait that long.)

I then added a loop to initialize the entire game field to non-nil before running the function. The result:

$ cat test.lua
local game_field = {}
local game_size = 1000000
local base_index = tonumber(arg[1])
print("Array indices start with "..base_index)

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

for j = base_index, base_index + 3*game_size - 1 do
   game_field[j] = "junk"
end

initialize_game_field()

$ time lua test.lua 1
Array indices start with 1

real 0m0.074s
user 0m0.066s
sys 0m0.008s

$ time lua test.lua 0
Array indices start with 0

real 0m0.076s
user 0m0.064s
sys 0m0.012s

Well then. Not only is there no significant difference between the two start indices, but both cases are roughly twice as fast as the original script starting at 1 (despite performing two loops over the array and twice as many assignments) and 6,000 times faster than the original starting at 0.

Perhaps the slowdown comes from assigning nils to fields that are already nil... but then why does start index matter?