Is there a faster alternative to table.remove during time-critical code sections?

yes thankx for the arguments i know it.

For the initial question, use that function to count the number of number-key element, it’s better than " #(table) "

local function hashtag(t) assert( t and type(t)=="table","not a good input for hashtag-function" ) local n=0 for ind in pairs(t) do if type(ind)=="number" then n=n+1 end end return n end local tab={} tab[1]="a" tab[5]="z" print(#tab) \>\>\> 1 print(hashtag(tab)) \>\>\> 2 (better :D)

for a global counting function, just remove the if-condition about the type of the key.

I have found for-pairs loops to be a lot slower in time-critical situations. If you know the fields that are in the table, it’s quicker to loop through using another table to lookup than k, v in pairs. If you extrapolate the below to hundreds or thousands of records with tens of fields, perhaps being processed many times a second, the first bit of code will be a lot quicker than the in pairs code, even if it is more long-winded.

[lua]

local fields = {“Name”, “Age”, “Address”}

local data = {

{Name = “Tony”, Age = 35 , Address = “Bolton”},

{Name = “Nigel”, Age = 56, Address = “Ipswich”}}

for a = 1, #data, 1 do

      for b = 1, #fields, 1 do

            local k = fields[b]

            local v = data[a][k]

           

            print (k, v)

      end

end

for k, v in pairs(data) do

      print (k, v)

end

[/lua]

…and if you take @nick_sherman’s approach and extrapolate it even further, perhaps to 10’s of thousands of records with dozens of fields, then don’t even hashtag your data fields, just imply them by position, and you’ll save both time and memory, fe:

-- field name forward lookup (ie, get name from index): local fieldNames = { "Name", "Age", "Address" } local data = { {"Tony", 35, "Bolton"}, {"Nigel", 56, "Ipswich"} } for recordNumber = 1, #data do for fieldNumber = 1, #fieldNames do -- "k" is NOT needed for RETRIEVAL at all -- provided only to have something for print() below local k = fieldNames[fieldNumber] local v = data[recordNumber][fieldNumber] print(k,v) end end

also fwiw, you might want a reverse lookup too:

-- field index reverse lookup (ie, get index from name): local fieldIndices = { Name=1, Age=2, Address=3 } for recordNumber = 1, #data do print(data[recordNumber][fieldIndices.Name] .. "'s age is " .. data[recordNumber][fieldIndices.Age]) end

if extending even further, perhaps 100 thousand records w hundred fields, then you might even want to break up the table into discrete indexed arrays of Name[n], Age[n], Address[n].  (bc each record takes 36 bytes, each hash take 40 bytes, while a numeric index just 16)  But… you would NOT want to do that if deletion (rather than storage/retrieval) is your primary concern!!

(also note that memory usage is heavier for a dynamically allocated table, compared to these static initialized examples)