Why is __newindex so slow?

Even without setting the table value, __call is faster (and with setting the table value __call is still faster)
But according to this amazing post https://devforum.roblox.com/t/roblox-altered-lua-quite-a-bit/35354/6
__call has a higher index on the (what is this thing called?) (I’m pretty sure its not called heap since its sorta global?)

local tick = tick
local count = 1000000


do
	local t = {}
	
	local start=tick()
	for i = 1,count do
		t[i] = true
	end
	print(tick()-start)
end

do
	--local rawset = rawset
	local t = setmetatable({},{
		__newindex = function(t,k,v)
			--rawset(t,k,v)
		end,
	})
	
	local start=tick()
	for i = 1,count do
		t[i] = true
	end
	print(tick()-start)
end

do
	local t = setmetatable({},{
		__call = function(t,k,v)
			--t[k] = v
		end,
	})
	
	local start=tick()
	for i = 1,count do
		t(i,true)
	end
	print(tick()-start)
end

These were my times:

0.028078317642212
0.061548948287964
0.05236554145813

I would assume it’s because newindex and call don’t function the same. Before newindex is called the system needs to make sure the index doesn’t already exist, which probably adds to the time. Notice it only has a small increase in time, not drastic. I could be wrong, but it makes sense to me that this is the case.

3 Likes