_G or ModuleScripts?

I’m reorganizing a 10k line script I have into multiple scripts and ModuleScripts, it has a lot of _G functions and it gets quite laggy after a bit of time, would it be better if I replace the _G functions with ModuleScript functions? Would it cause any less/more lag or will it change nothing?

4 Likes

ModuleScripts are a much better option and is definitely what Roblox is trying to lean developers towards. In my experience _G. is less efficient, causes lag and is less favorable.

4 Likes

Thanks alot, I will stop using it

1 Like

I certainly agree that ModuleScripts are favorable, but where do you get the idea that _G is inefficient and causes lag?

It seems it would be basically the same performance-wise.

3 Likes

_G only causes lag when waiting for keys to load in at the top of the script like this:

while not _G.MyLibrary do
    wait()
end

I wrote plenty of code like that before ModuleScripts were implemented, but I don’t recommend doing anything like that today, as it can take seconds for dependencies to snap into place.

Although it is very bad practice to store mutable variables in _G, _G can be extremely helpful for quickly referencing your immutable utility functions/classes in large-scale projects. Accessing _G is quite fast, just be careful and only do it from ModuleScripts so you can safely assume _G is populated before your code runs.

Also, when developing free models, gear, or scripts that run in large ecosystems of unknown scripts, it is important to either use extremely unique keys, only add temporary keys before ModuleScripts are required, or not use _G at all.

12 Likes

Thank you for your explanation. I had not used _G. much myself so I didn’t know what caused the lag but merely have been told it does so. Thanks for expanding my knowledge.

2 Likes

I say it’s a matter of preference. Yes, ROBLOX has made ModuleScripts as an alternative to _G and which I prefer due to the features they provide (loading by AssetId, private source code, etc). However, _G is a perfectly fine use case if that’s what you prefer for your personal projects. Public projects is where I’d lean to say for sure use ModuleScripts simply to ensure no conflicts or other potential issues

4 Likes