What is the most efficient way to handle events in this case?

Hi, I have a question. When we have to do many things within a particular event we can do it in two ways

a) create many functions and put them within a connection to the event, for example:

local doSomething1 = function () ... end
local doSomething2 = function () ... end
...
local doSomethingN = function () ... end
SomeObject.SomeEvent:Connect(function (...)
	doSomething1(...)
	doSomething2(...)
	...
	doSomethingN(...)
end)

b) or create many connections to the event, one for each thing

SomeObject.SomeEvent:Connect(doSomething1)
SomeObject.SomeEvent:Connect(doSomething2)
...
SomeObject.SomeEvent:Connect(doSomethingN)

How are they different? Which is more efficient? The more detail the better.

If you use example A the functions will be run sequentially when the event fires, meaning doSomething2 won’t run until doSomething1 is finished.

In example B the functions will run concurrently. Since they are in separate threads they will execute at roughly the same time but there is no guarantee of the exact order they will be called.

I guess it sort of depends on what those functions do, whether they are asynchronous or have yields or somehow rely on each other.

in case b) many threads are created. Do many threads affect overall performance? How many threads is too many?

You should definitely go with option A, option B is poor practice and it is good practice to have one listener per remote for making validating and debugging easier, there is also a known bug with using multiple connections on the same remote: RemoteEvent fires before :connect returns - #4 by Anaminus, Remote Events in Multiple Scripts - #5 by Anaminus, Basically it will cause connections to miss fired signals, so for every remote event only use OnClientEvent and OnServerEvent once.

1 Like

That rule currently applies only to RemoteEvents, not events in general.

As for performance, listeners will reuse threads when they can:

Oh yes I know that is why I said OnClientEvent and OnServerEvent, but I was not sure if the person was using remotes or bindables.

wow. thanks, this information is very useful.

1 Like