Efficiency with events and connections

Many of my game’s core mechanics rely on firing events (Bindables, mainly) and listening to them from other scripts.

I want to know which of the following event setups is more performant:

  1. One pre-setup BindableEvent (e.g. placed in StarterPlayerScripts or ServerStorage) with multiple connections (10+ possibly across multiple scripts, and the connections are disconnected when not needed). Same with RemoteEvents; there won’t be exactly one, but there will be a few with numerous connections each.
  2. Multiple (~5-10) BindableEvents that are dynamically created (with Instance.new) when a function is called, each with one or two connections (possibly across multiple scripts); the BindableEvents and connections are cleaned up when they aren’t used (in my case, it’s when a player dies). Same with RemoteEvents; they are created server-side parented to ReplicatedStorage.

I’m using setup 2 for most of my scripts. If there’s an even better way to handle events, please let me know.

2 Likes

to boost your event setups a bit further, you should definitely check out this signal class. it’s pretty much 1-to-1 with BindableEvents.

So it would be a good idea to replace the BindableEvents with signals if I’m dynamically creating them?

So this:

function Class.new()
	local self = {}
	
    self.SomethingHappenedEvent = Instance.new("BindableEvent")
    self.SomethingHappened = self.SomethingHappenedEvent.Event

	return setmetatable(self, Class)
end

object.SomethingHappened:Connect(function()
    print("Fired")
end)

becomes this:

function Class.new()
	local self = {}
	
    self.Signal = Signal.new()

	return setmetatable(self, Class)
end

object.Signal:Connect(function()
    print("Fired")
end)
function Class.new()
	local self = {}
	
    self.Signal = Signal.new()

	return setmetatable(self, Class)
end

object.Signal:Connect(function()
    print("Fired")
end)

yeah, thats it!!!

one cool thing that you can do with signals is that if you wrap them with cleanup libraries like Janitor, you can destroy the cleanup object and the signals attached will be destroyed along with it.

signals are really cool to use overall, hope you have fun playing around with 'em!

BindableEvents are just old and they leak memory a lot of times without you knowing because Instances obey different memory leak laws, because of the C → Luau bridge which doesn’t get all context possible shared through them.

It has been quite a while since Bindable based signals where replaced with Luau implementations. They’re slower and cause more memory leaks, hence why you should upgrade to something like GoodSignal, my Signal implementation, sleitnick’s GoodSignal mod, and others.