Is it bad to require a module several times in 1 script?

Is it a bad idea to require the same module script over and over instead of dumping it into a variable? Does this affect memory or server performance?

For example: Which of these will be better?

A

local MyFunction = require(script.module)

for i = 1, 100 do
   MyFunction()
end

B

for i = 1, 100 do
   require(script.module)()
end

C (Don’t use the module at all)

local function MyFunction()

end

for i = 1, 100 do
   MyFunction()
end

Please put everything in order of best.

  1. A
  2. B
  3. C
1 Like

Does this affect performance?

Yes, everything affects performance. But does it meaningfully affect performance? No, Roblox caches the require result after the first time a script has been required, so you’re just being handed the same result in a different manner.

The time difference with a loop running one million times is 0.1275ms vs 0.0503ms

The performance difference is very negligible so you should do whatever makes sense for your implementation. Don’t waste your time thinking of optimization in regards to minor stuff like this, it’s always unimpactful. You bring up memory but think about it, how much memory could the variable possibly take?

Also, you can easily write a test for your situations and then benchmark them. Just time the execution over a set amount of iterations, then compare. Measuring is always best if you’re in doubt.

4 Likes

Thanks for your reply!--------

I have an onserverevent function that requires a module with the name sent e.g

Event.OnServerEvent:Connect(function(plr, info)
  local module = require(script[info]
  module.Run()
end)

But I’m not quite sure if it’s the right way to go about this.

2 Likes

Thank you! your and other answers from the forum helped me come to the following solution:

  1. A, С
  2. B
1 Like

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