Caching components other than GameObjects and Transforms

I have a script which accesses the gameobject’s material to change its color or switch it out for another material. I know that caching references to a GameObject or Transform will reduce the load on the cpu because of the hidden GetComponent() call.

Does this hold true for renderers and/or materials?

I’m guessing that GameObject variables that are ultimately derived from Component have a hidden GetComponent calls. Material is not a GameObject variable, and it is not derived from Component. It is derived from Object and is a variable of the Renderer class. Cashing a Material will save you one indirection, but it will not save you a GetComponent call. Caching the Renderer will save a GetComponent call.

You can check what they are derived from by following the chain back in the script reference. For example, ‘hingeJoint’ is a GameObject variable. If you look at the reference page for ‘HingeJoint’, you will see it inherits from ‘Joint’, which in turn inherits from ‘Component’.

The best way to test it, it’s to benchmark. Make a loop with like 1 million (or more) iteration with an access to renderer directly and an another with an access to the cached renderer value. And compare the time between the two, you will have your answser.