Performance impact of not setting GetService returns as variables?

I currently have 86 instances of GetService in my code because I was too lazy to set them as variables at the beginning of my code; Obviously this is horrible practice. But just how bad is it?

What about something like this?

services = setmetatable({}, {__index = function(self, index) services[index] = game:GetService(index) return services[index] end})

services.DataStoreservice
services.MarketplaceService

Note:
This doesn’t actually serve a purpose to me as I’m adding them at the top of my code anyways. This is more of a curiosity thing.

2 Likes

It’s probably not that bad. If you’re doing it hundreds of times in an infinite loop it might matter but otherwise its neglible. You might get tired of writing game:GetService though.

I know for a fact some people use a table of services like you suggested, though I would advise against it since it reduces readability.

3 Likes

while game:GetService(“RunService”).RenderStepped:wait() do
–code
end

seems like it would cause a problem because it’s being run ~60x per second

going to do some experimentation with a few different methods in a blank baseplate.

RunService = Game:GetService(“RunService”)

While do

RunService.RenderStepped:Wait()
—Code
End

On phone rn so if u correct typos and stuff this should be more efficient

After some testing, performance impact is negligible with 1000+ iterations

I doubt it makes a large impact at all, but if you’re worried about the potential impact of :GetService() then you could always log previously indexed services for later use. Though I have no idea if this would be any more efficient.

local Services = setmetatable({},{
	__index = function(t,k)
		local Service = game:GetService(k)
		t[k] = Service
		return Service
	end
})

https://developer.roblox.com/en-us/api-reference/function/ServiceProvider/GetService

Reading this the phrasing seems to suggest caching, so you are just grabbing a reference to an existing service for each subsequent call.

Main purposes seem to be generating non default services and ensuring the acquisition is a service

For services that aren’t around normally you might see some divergence in performance. If say lua GC’s the generated service due to no reference maintained.

This is not necessary. If __index is being fired then the index did not exist previously to begin with.

3 Likes