Is it okay to store module functions/values?

Let’s suppose I have this module:

local _M = {}

function _M.SayHello(plr : Player) : ()
    print("Hello,", plr.Name.."!")
end

return _M

And this script:

local plrs = game:GetService("Players")

local _M = require(path.to._M)

plrs.PlayerAdded:Connect(_M.SayHello)

I wish to know if it is, not visually speaking, but about efficiency, better to store the function outside the PlayerAdded; such as this:

local plrs = game:GetService("Players")

local _M = require(path.to._M)
local sayHello = _M.SayHello

plrs.PlayerAdded:Connect(sayHello)

There should be no performance degradation, it’s a matter of preference and ease of reading.

It’s really not going to affect performance? Because when you don’t store it, you are indexing it all time. Imagine I have a loop using this function, wouldn’t it affect performance by indexing it each run?

In your example you’re not indexing it everytime as you’ve localized the function to the scope of the script. It makes no difference in this case. Even if you were indexing it repeatedly, it would cause negligible difference as long as the module storing the functions wasn’t insanely large where after every index it has to search through a crazy amount of functions.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.