Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Would constantly using GetService be less efficient then defining the Service only once?

Asked by
3dsonicdx 163
8 years ago

Stupid question - but wondering if it's any more optimal or it just looks prettier.

Like would

local debris = game:GetService("Debris")

for i=1, 10 do
local d = Instance.new("Part")
d.Parent = game.Workspace
debris:AddItem(d, 2)
end

Be more efficient than


for i=1, 10 do local d = Instance.new("Part") d.Parent = game.Workspace game:GetService("Debris"):AddItem(d, 2) end

1 answer

Log in to vote
1
Answered by 8 years ago

It would be more efficient to use the first as it means that GetService is only called once rather than 10 times. If you wanted it even more efficient, you could do this:

local debris = game:GetService("Debris")
local addItem = debris.AddItem

for i=1, 10 do
local d = Instance.new("Part")
d.Parent = game.Workspace
addItem(debris, d, 2)
end

But you really shouldn't worry about performance unless it's a big issue e.g. running a loop a very large number of times. Do whatever looks neater.

Ad

Answer this question