[SOLVED] Is cacheing a 'get' still useful?

I’ve been perusing the code of some scripts from a few assets from the Unity asset store and I’ve noticed sometimes components of the ‘gameObject’ will be cached (usually the transform). Something like:

 private Transform thisTransform;

void Awake () {
    thisTransform = gameObject.GetComponent<Transform>();
}

(for example)

From what I’ve read, this was common practice in Unity 3 and earlier as ‘GetComponent’ was a costly function (and gameObject.Transform is a ‘get’).

Is it still good practice to do this? Is there any noticeable performance boost or are these just code relics from the old days? I’m not one to fuss over every smitch of performance but I would like to make an informed decision on whether or not to practice this in my own code.

Thank you, LeftyRighty. Exactly the thread I wanted.

For anyone else who ends up here- the short answer is NO it’s not necessary to cache

Edit: The thread basically shows the difference is measurable but not noticeable. The short answer for my question is that cacheing doesn’t matter. The immediacy of a differing opinion below suggests any curious users who make it here should read the thread and decide for themselves- there are even some cool tests in there!

To clarify, it’s not needed to cache Transform. Everything other GetComponent call should still be considered for caching.

1 Like