Hey folks,
this is not a specific Unity question, but maybe interesting (or not) for game development in general.
I was wondering if it makes a difference if I try to read a variable directly several times in a single update loop, or if it would be better (performance and memory) to save the variable temporary (see Example 1, Example 2 and Example 3 below).
On the one hand we can consider that a stored variable needs virtual memory of the random access memory (RAM). On the other hand it needs performance of the graphic card or rather the processor (core) to read a variable.
Maybe some questions a pro or person with knowledge and/or experience can answer:
-
Is there a difference in performance and memory?
-
If yes, how can we observe the impact?
-
Is there a break even point, when it makes sense to use the one solution or the other?
-
Whats better to read and debug?
using UnityEngine; public class Excample : MonoBehaviour { private Animator animator; private float tmpFloat; private float animatorFloatValue; // Update is called once per frame void Update() { //Example 1: (float reads: 1, float saves: 2) tmpFloat = animator.GetFloat("My Animator Float"); animatorFloatValue = tmpFloat * tmpFloat; animator.SetFloat("My Animator Float", animatorFloatValue); //Example 2: (float reads: 2, float saves: 1) animatorFloatValue = animator.GetFloat("My Animator Float") * animator.GetFloat("My Animator Float"); animator.SetFloat("My Animator Float", animatorFloatValue); //Example 3: (float reads: 3, float saves: 0) animator.SetFloat("My Animator Float", animator.GetFloat("My Animator Float") * animator.GetFloat("My Animator Float")); } }