- Home /
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?
In the first caching example, I don't think you even need to use GetComponent, do you? Can't you just say:
private void Awake() {
cachedRigidBody2D = rigidbody2D;
}
I mean, it's an inherited variable so no need to waste the extra time to perform GetComponent, even in the Awake method. Then your cached variable will run slightly faster than the pre-defined inherited variable, as chirhotec showed below.
Answer by chirhotec · May 15, 2014 at 07:35 PM
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!
===============*
Your answer
Follow this Question
Related Questions
Get OnMouseUp event in other object's script 1 Answer
Speed and efficiency of enabling/disabling component? 1 Answer
Show enabled flag on custom components that don't use Unity event functions? 0 Answers
Copying a Component's values without a new Game Object 1 Answer
Create a method that gets called everytime something happens, passing a Transform component to it 1 Answer