Should it be improved? I’m a new developer, and I’ve heard that having one connection is better than multiple connections. (google translate)
Handler:
local RunService = game:GetService("RunService")
local __public = {}
local __private = {}
__private.connection = nil
__private.functions = {}
function __public.Main()
__private.connection = RunService.Heartbeat:Connect(function(deltaTime)
for _, func in pairs(__private.functions) do
coroutine.wrap(func)(deltaTime)
end
end)
end
function __public:Connect(funcName, func)
__private.functions[funcName] = func
end
function __public:Disconnect(funcName, func)
__private.functions[funcName] = nil
end
return table.freeze(__public)
Example:
local Heartbeat = require(script.Parent.Heartbeat)
function Main()
Heartbeat:Connect("Test", function(deltaTime)
print("Test")
end)
end
return { Main = Main }
I’m assuming you’re coming from another platform? The way you format your code, seems strangely reminiscent of C#. But that’s a bit of an aside.
Getting on topic, the question of whether less connections should be preferred over more connections, doesn’t have such a clear cut answer. Thread objects (the objects which represent coroutines in Lua/u) are quite cheap in memory. Having multiple threads which are static is fine. The danger is inadvertently creating lots of temporary threads on the frame, which consistently put otherwise avoidable strain on the garbage collector. Roblox’s implementation of Connections is smart, in that ordinarily, connections will recycle the same thread to handle callbacks in. Where this falls apart however, is when the connected function yields. If the function yields, there’s no guarantee that the thread will be available to handle the next callback, and so rather than recycling the same thread, the connection creates a new one.
Here, by merging together callbacks into the same connection, you take functions which may have otherwise ran in the same thread, and guarantee that new threads will be created, by explicitly calling coroutine.wrap. Unless every one of these callbacks would have yielded anyway, this approach is undoubtedly more costly than if you had just opened separate connections for each of them.