Hello again, guys.
I recently found a good thread here about caching GetComponent calls, since they’re apparently fairly slow. Since then, I’ve been scanning all my code for such calls in Update and elsewhere and replacing them with cached variables wherever it’s possible to do so.
My question, though, is this: Should anything aside from "Get"s be cached? For instance, if I want to rapidly assign an intensity value to a light within Update, should I cache my gameObject.light into some sort of MyLight variable to enhance performance, or are these not the same as GetComponent calls?
GetComponent is not really slow. If you’re only accessing it once per frame, caching it is not going to make any measurable difference (a decent CPU could do 10+ million GetComponent calls per second), so it’s not likely to be worth using up more memory by caching it. Anyway, “
gameObject.light” is the same as “
gameObject.GetComponent(Light)”. I’d only bother with caching if you’re heavily using that component.
The various Find commands, on the other hand, are always worth caching.
The rule of thumb I go by is if you’re accessing any component in an update loop then it’s best to just cache it locally to prevent any ‘find’ operation that might be hidden by a property Get. I.e. this.transform (might or might not) refind the transform every time it’s queried. So to be safe it should be cached.
Yeah, any ‘Find’ operation for example is a good thing to do once.