What is good, table.remove or table[i] = nil?

‘for i,v in ipairs’ is more better than 'for i,v in pairs’ at performance.
‘t[i] = nil’ is better than ‘table.remove(t,i)’.

I need to remove and add frequently from a table and Iterate the table 60 times per second.
like this:

local ActiveArrows = {}
spawn(function()
	(IsClient and RenderStepped or Heartbeat):Connect(function()
		for self,v in pairs(ActiveArrows) do / for i,self in ipairs(ActiveArrows) do 
			if self.Destroyed then
				ActiveArrows[self] = nil / table.remove(ActiveArrows,i)
			else
				--do something
			end
		end
	end)
end)
function module.NewArrow(chr,Object,Power,Direction,PartMode,CollisionGroup)
	local NewArrow = setmetatable({},Arrow)
	ActiveArrows[NewArrow] = true / table.insert(ActiveArrows,NewArrow)
	return NewArrow
end

What is better at performance?
It’s a dilemma to me :frowning:

The difference in performance between the two should be minimal and (probably) something you shouldn’t worry as much about when working on Roblox, where micro-optimisations are rarely impactful. Having said that table[i] will most likely be faster since it isn’t calling a function.

The difference is that when you do table[i] = nil, the index i, is not removed from the table, but just set to nil:

local tab = {2, "string", 5, 7}
tab[2] = nil
print(tab) -- {2, nil/void, 5, 7}
print(#tab) --4
--Now tab looks like this, with the same length: {2, nil, 5, 7}

image
void = C++'s nil

Unless you set the last object of the table to nil (tab[#tab] = nil or tab[4] = nil):
image


When you do table.remove, you completely remove i from the table, and all objects after i go one index backwards:

local tab = {2, "string", 5, 7}
table.remove(tab, 2)
print(tab) --{2, 5, 7}
print(#tab) --3
--Now tab looks like this, with the shorter length: {2, 5, 7}

image
I do not think there’s a need to worry about performance. And even if there is, it is probably neglectable.

I suggest you to use table.remove

1 Like