Caching Variables in Unity

Today I was reviewing some Unity code and I got puzzled by this statement

private Rigidbody _cacheRigidbody;
void Start () { 
      // Cache reference to rigidbody to improve performance
      _cacheRigidbody = rigidbody;

At first glance, I couldn’t understand what is the scope of declaring a cache variable when it is just referencing the same memory space.

Well…according to the Unity it is faster to cache the reference to the object on start() or awake() method, rather than use the GetComponent<Rigidbody>() or GameObject.Find() everytime you want to use a component.

Reduce GetComponent Calls

Using GetComponent or built-in component accessors can have a noticeable overhead. You can avoid this by getting a reference to the component once and assigning it to a variable (sometimes referred to as “caching” the reference). For example, if you are using something like:-

function Update () {
    transform.Translate(0, 1, 0);

…you would get better performance by changing it to:-

var myTransform : Transform;

function Awake () {
   myTransform = transform;

function Update () {
    myTransform.Translate(0, 1, 0);

Well that make sense now! 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s