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

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

Be more efficient than

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

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:

1local debris = game:GetService("Debris")
2local addItem = debris.AddItem
3 
4for i=1, 10 do
5local d = Instance.new("Part")
6d.Parent = game.Workspace
7addItem(debris, d, 2)
8end

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