Essentially I’m trying to find out whether I should be storing a reference to the service I retrieve or if I can simply call GetService every time I need it.
A perfect example of what I’m using this with is SpriteBatch. Instead of having an object store a reference to the SpriteBatch, I call
SpriteBatch spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
at the beginning of every Draw() method that needs it.
In conclusion, what is the Big O of GetService()? This will help me decide. I’m assuming it’s a hash table so generally O(1)?
The Big-O of
GetServiceis irrelevant, because you have a small and constant number of services in there. So effectively callingGetServiceis a constant-time O(1) operation. (Internally it uses aDictionary– I couldn’t easily track down a definitive answer on its Big-O, but I imagine it’s pretty good).Is it a lot slower than getting a reference? Yes.
Is it too slow for a game world with, say, 100 gameplay objects? No.
Is it too slow for each of 100000 particles in a particle system? Yes.
Is using a services architecture for this a bad idea, even if you ignore performance and consider only an architectural point of view? Yes.