Is it very bad performance-wise when using require() often, and how would I prevent require overuse?

Just a quick question! Right now I’m working on a game which has abilities/powers, and I’m putting modules in a specific hierarchy like: Main Ability Handler > Ability Type (i.e magic abilities) > Abilities (fireball, frostbreath, etc). What I’m planning to do is, on request, the Main Ability Handler will require the specific Ability Type and then the ability type module will require the specific Ability. The problem with this implementation however is that I would need to require the modules everytime I want to activate an ability (which will happen often).
So, like the title asks: is it bad performance-wise using require() that often, or is it fine?
Also: how would you specifically make a work-around/performant way of doing this? I’m thinking of maybe storing the required modules in an array, so require would only run on first-time usage of an ability, and the rest of the time it would just get the module from the array.
Would be great to hear how you guys would implement this :slight_smile:

2 Likes

Calling require does not have a performance impact, however you may want to be careful when requring a module by an ID as this sends an API request.

1 Like

Which should be cached, in theory. So it would, in theory, only send one API request once.

@bjarkibjarki if you don’t want to call require, you can put them all in a table at the start of the script. That’s a pretty common practice.

local attacks = {
    fireball = require(script.Fireball),
    fireballButBigger = require(script.HugeFreakingFireball)
}

But it isn’t anything to worry about. The modules only run once, and then they cache. So you call require() the first time on a module, and that module initializes. From then on, the module is already initialized and calling require() on the same module will not have any more impact than a regular function call.

local var = require(module)
local function req()
    return var
end

req()
require(module) -- approximately the same execution time.
    -- i.e. negligible and nothing to worry about because Roblox can't read
    -- player inputs fast enough for this to ever matter.
7 Likes

If the vfx modules share a common parent you can create a module that simply loads in and caches those modules in a table and has a function to query the respective module. Could look something like this:

local VFX_DIRECTORY = script

local VisualEffectMap = {}
for _, child in ipairs(VFX_DIRECTORY:GetChildren()) do
    VisualEffectMap[child.Name] = require(child)
end

return VisualEffectMap

Personally, I use the some procedure you described when it comes to abilities and have tested it on a large scale and haven’t really seen any performance issues regarding the usage of require.

1 Like