Is it better to set the table to empty or set all table elements to nil?

The question about a piece of lua code came up during a code review I recently received. This code is clearing the cache and reinitializing it with some data:

for filename,_ in pairs(fileTable) do
    fileTable[filename] = nil
end

-- reinitialize here

Is there any reason why this cycle should not be replaced?

fileTable = { }

-- reinitialize here
+5
source share
3 answers

/ . , . , , 1. , . , , ( -) . - 2, . . rehash , , 0, 1, 2, 4, 8 .. .

, , , Lua . , /-, ( ) , , .

Update:

:

local function rehash1(el, loops)
    local table = {}
    for i = 1, loops do
        for j = 1, el do
            table[j] = j
        end
        for k in ipairs(table) do table[k] = nil end
    end
end

local function rehash2(el, loops)
    for i = 1, loops do
        local table = {}
        for j = 1, el do
            table[j] = j
        end
    end
end


local function test(elements, loops)
    local time = os.time();
    rehash1(elements, loops);
    local time1 = os.time();
    rehash2(elements, loops);
    local time2 = os.time();

    print("Time nils: ", tostring(time1 - time), "\n");
    print("Time empty: ", tostring(time2 - time1), "\n");

end

. test(4, 10000000) Lua 5.1 7 nils 10 . 32 ( , ). test(128, 400000) 9 5 .

LuaJIT, alloc gc , test(1024, 1000000) 3 nils 7 .

P.S. Lua LuaJIT. 1024 Lua 100 000 20 , LuaJIT 1 000 000 10 !

+2

, Lua: , , .

+4

- Lua ( ). , "", GC, , , - , GC .

In your example, the technician processes these flaws in the time required to explicitly delete all the elements in the table. This will always save memory and, depending on the number of elements, can often be a performance improvement.

0
source

All Articles