This is something that came to mind about a week ago, and I haven't been able to stop thinking about ever since.
To clarify on what I'm talking about: If I were to to give an anonymous function to a connect event, would it create a new function each time it gets invoked?
Example:
local RunService = game:GetService('RunService'); -- This would create a new function upon each iteration -- which is completly unnecessary when you could -- just define it before the loop. while wait() do local test = function() end end -- Would this be doing the same as above? RunService.heartbeat:Connect(function() end) -- Would this be a better choice? local update = function() end RunService.hearbeat:Connect(update)
i mean, it doesn't really matter in this case, but it does matter when you have nested loops and events...'
when you do object.EventName:Connect(f)
where f
is a function, the Roblox event loop stores the function and calls it whenever the event occurs.. and therefore you only have a single function in memory..
but when you have nested loops, its best to put a function in a variable, other wise the loop will keep allocating memory with each iteration.. for example:
local Players = game.Players local players = Players:GetChildren(); for _, player in pairs(players) do player.SomeEventName:Connect(function() print("Something happened") end) end
if the above code ran when there is 30 players in the server, it means Lua will allocate memory for 30 functions, because on each iteration we call Connect()
with a new function.. the more memory we allocate, the less memory we have to run other things, and the poor the performance of our game.. and that's what we call a Memory leak
so in this case, it would be a great idea to put a a function in a variable, and just pass that one function to each call to Connect()
.. here is the same, but efficient version of the above code
local Players = game.Players local players = Players:GetChildren(); function onSomeEventName() print("something happened") end for _, player in pairs(players) do player.SomeEventName:Connect(onSomeEventName) end
in this version, all the calls to player:Connect
are passed a single function, and therefore, only 1 memory allocation is done for the connecting functions..
remember, every variable that we create takes up memory, therefore, only declare variables when you'll only need them.. for example:
variables that you will use in a function
should be declared in a function..
whenever a function
returns, Lua will automatically return the memory it allocated, giving us more memory to do more things, whenever you set a variable to nil
it also helps in returning memory..
Nope, it creates a new function once and precisely once.
Storing them beforehand is a better choice if you're connecting it to more than one event. (see: something of the likes of this)
--... local f=function() end EventA:Connect(f) EventB:Connect(f) --...
Otherwise, anonymous functions do the trick just fine.