Are these the same: require()

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

VS

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

Do they do the same?

The semantics are equivalent but the former will probably run significantly faster, depending on what happens when you call m().

4 Likes

Why so?

One is a function call of a local variable, while the other involves calling into the Roblox engine into a bunch of machinery that will ultimately figure out that the module has already been require()d and cached into a table, and return that cached result.

The reason the semantics are equivalent is because require() caches the result of executing the modulescript.

4 Likes

If require() is called in a scope, will it get gc’d?

As far as I know, the cached result of executing a modulescript will not be GCed until the ModuleScript itself is garbage collected, when it gets :Destroy()ed.

How about if the module returns a value? Will it get GC’d?

That is what gets cached.

There has been a surprising increase of posts regarding Garbage Collection and memory efficiency in these past few days.