Which is faster, multiple connections, or one connection and a table?

Basically, I want to know if this is faster:

local callbacks = {}

something.Event:Connect(function()
    for _, callback in ipairs(callbacks) do callback() end
end)

callbacks[1] = function() ... end
callbacks[2] = function() ... end
callbacks[3] = function() ... end

Or this:

something.Event:Connect(function() ... end)
something.Event:Connect(function() ... end)
something.Event:Connect(function() ... end)

What are your thoughts on this? I theorize that multiple connections should be faster, since Roblox is supposed to be performant with connections and iterating through a table in Lua is slower than C, but I’m not sure. I have not done any tests on this.

2 Likes

Multiple connections

Multiple connections isn’t my favourite, since the functions will only get GC’ed if the Connection is Disconnected.

I tried it out with this code:

local Bindable = script.Event

Bindable.Event:Connect(function(Time)
	print("1 Connected at " .. tick() .. ", difference: " .. tick() - Time)
end)

Bindable.Event:Connect(function(Time)
	print("2 Connected at " .. tick() .. ", difference: " .. tick() - Time)
end)

Bindable.Event:Connect(function(Time)
	print("3 Connected at " .. tick() .. ", difference: " .. tick() - Time)
end)

Bindable:Fire(tick())

And got these results:
Image
As you can see, the third connection infact gets called so quickly it’s scientifically notated. Strangely enough, they get called in inverse to how they were connected.

Function array

I prefer this version since only one connection is added.
However, the callback may need to be coroutine wrapped if it yields otherwise the other functions will be held back.

I tried it out with this code:

local Bindable = script.Event
local Array = {
	function(Time)
		print("1 Connected at " .. tick() .. ", difference: " .. tick() - Time)
	end,
	
	function(Time)
		print("2 Connected at " .. tick() .. ", difference: " .. tick() - Time)
	end,
	
	function(Time)
		print("3 Connected at " .. tick() .. ", difference: " .. tick() - Time)
	end
}


Bindable.Event:Connect(function(Time)
	for _, Function in ipairs(Array) do
		Function(Time)
	end
end)

Bindable:Fire(tick())

And got these results:
Image
This time they were chronological and astronomically faster, the last function connected at 0.05 compared to 0.11.

Conclusion

Based on these results, an array was found to be faster.
Do note that here I used a BindableEvent and it was only one test, results may mutate for RemoteEvents.

An array of functions is most probably easier to work with as well, additionally having so many Connections can be hard to Disconnect.

8 Likes