Caching a Monobehaviour Component's reference properties (rigidbody2d, specifically)

I’m in a live training session (not Unity official), and the instructor is saying that everytime you call this.rigidbody2d, the rigidbody2d getter is essentially calling GetComponent(). This of course is pretty slow, so he’s recommending we cache the reference on Awake().

Essentially, he is saying this:

public class MyClass : MonoBehaviour {
    private Rigidbody2D cachedRigidBody2D = null;

    private void Awake() {
        this.cachedRigidBody2D = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate () {
        cachedRigidBody2D.AddForce (Vector2.up);
    }
}

Is more efficient than this:

public class MyClass : MonoBehaviour {

    private void FixedUpdate () {
        this.rigidbody2d.AddForce (Vector2.up);
    }
}

I’ve been using Unity for years and have never heard of this. Seems like a pretty important optimization to always make given how frequently you’d typically reference these built-in component properties. Does anyone know if this is accurate?

Okay, I just did some some tests, and the cached version is actually faster! (though referencing this.rigidbody2d isn’t nearly as slow as GetComponent();

For details, here’s the test:
I set up a loop in the Update() function that runs 1 million times per frame.

  • Test 1: no loop => ~80 FPS
  • Test 2: Using the cached reference [cache2 = cachedRigidBody2D;]=> ~80 FPS, maybe slightly slower
  • Test 3: Using the built in reference [cache2 = this.rigidbody2D;] => ~45 FPS
  • Test 4: Using GetComponent [cache2 = GetComponent();] => ~5 FPS

The More You Know!

===============*