Using Global Variables for Improved Performance

I have a folder called DataHub located in Workspace, which contains several IntValues and StringValues. Multiple scripts access and use these values for their tasks.

Today, I learned how to use Global Variables and am considering if it would be better for performance to store all these values in a script within ServerScriptStorage as Global Variables instead of using the current setup.

For example:

NeededPlayers = 1
GameTime = 30

Would this approach improve performance?

This approach would make performance worse, as global variables require an additional table lookup to be accessed.

Also, simply defining your variables like that will not make them accessible outside of the script they were defined in. You’d instead have to use something like _G, which is not recommended. If you want variables easily accessible from anywhere, you should use a ModuleScript.

1 Like

If all the values are only being accessed on the server then I would recommend using a module script to store these values.

For example:

local DataHub = {
NeededPlayers = 1,
GameTime = 30,
}

return DataHub

Accessed like this:

local DataHub = require(path.to.module)

print(DataHub.NeededPlayers)
print(DataHub.GameTime)

If you don’t use the word local it doesn’t become global as in global to all scripts. It becomes global to that single file. If you want a global variable for all scripts you can use _G or shared. It’s not recommended to do so for organization purposes and instead you should use ModuleScripts.

Global Variables

  • Pro: Faster access since they are stored in memory.
  • Con: Can become hard to manage and track in large scripts.

Instance Values (IntValues, StringValues, etc.)

  • Pro: organize and modify easily
  • Con: Slightly slower access due to interaction with the Roblox object hierarchy.

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