- Home /
Should we always cache local variables in classes?
Compare two scripts:
public class MyClass1 : UnityEngine.MonoBehavior
{
void Update()
{
float x = transform.position.x / (transform.position.y);
Foo(x);
}
void Foo(float _x)
{
// magic with _x
}
}
and
public class MyClass2 : UnityEngine.MonoBehavior
{
float x;
void Update()
{
x = transform.position.x / (transform.position.y);
Foo(x);
}
void Foo(float _x)
{
// magic with _x
}
}
So the only difference between MyClass1 and MyClass2 is that all local variables are cached into private fields in the latter. Is it prefable to do this? Intuitively to me, it seems that for any variable, it is much cheaper to declare the variable type first and then just overwrite it whenever you need to, rather than telling the compiler to create a whole new variable every time the method (Update(), in my example) is called.
Put another way, why would you EVER want to create a variable within a class method, rather than use a private field?
Calculating an int (should be a float, honestly, based on your snippet), is much faster than for instance GetComponent<T>
. You should absolutely cache anything where you use GetComponent, and it can be in local scope - doesn't have to be class scope. Caching primitive types, however, basically comes down to style, personal preference, and use case. For instance, if you need to monitor changes to a variable, then you'd need to cache it at class scope. If it's going to get calculated every frame and you expect that its value will change in the same, there's no need for caching.
Ahh yeah I should have used float, but to be honest my question wasn't really about ints or floats or strings or any other struct or class! I'll edit it to avoid confusion though. I understand you are saying that primitives probably don't need to be cached in such cases... but is there any harm? $$anonymous$$y preference is to cache absolutely everything and keep variable-creations down to an absolute $$anonymous$$imum, and I'm wondering what disadvatages there are to my approach? (And if none, why doesn't everyone do this?)
Like I said, it's developer preference. $$anonymous$$eeping variable declarations down means you're using less of a memory footprint which is fine, but allocating a primitive doesn't cost much memory either. You'd have to start really getting into lower-end platforms like phones or extremely old consoles to have 4 byte primitives start to matter. You may have the GC start causing issues if you declare hundreds of variables, but its impact is negligible if you have only a few assignments.
Using locally scoped vars makes code easier to read. The increase in memory footprint is a price worth paying so that you don't have to F12 everywhere to understand what's happening with code.