Caching uses 8 lines of code vs non-caching using 4 lines of code

Howdy.

I understand you’re teaching caching as well as using IF statements. Below is the code I did as my own code challenge before I watched you introduce the caching variables approach. It only needs 4 lines of code without using caching variables and is a simple copy and paste to the Update () and then changing the false values to true.

Once I saw your use of caching variables I refactored my code to use them. I see the value of using caching variables in more complex code blocks.

Jim

void Start()
{
     GetComponent<MeshRenderer>().enabled = false;
     GetComponent<Rigidbody>().useGravity = false;
}
void Update ()
{
     GetComponent<MeshRenderer>().enabled = true;
     GetComponent<Rigidbody>().useGravity = true;
}

While I have my suspicions that code won’t run, as you can see above, technically, you can do it with a single line of code but it makes it unnecessarily difficult to read.

Caching has its own set of problems but you’d be better off focusing whether you should cache or not (and on readability of your code) rather than worrying about the number of lines of code.

Hi FairlyGreen,

Welcome to our community! And good job on challenging yourself! :slight_smile:

Update gets called once a frame meaning multiple times per second. Generally, if we access the same “other” objects multiple times during the lifetime of an object, we prefer to cache the references for reasons of performance. GetComponent is a rather slow method. If GetComponent had not been a rather slow method, your solution would have been perfectly fine. Readability is more or less a matter of personal preference while performance is something we can objectively measure, for example, in the profiler in Unity.

I hope this cleared things up a bit further. Keep up the good work and do test your own ideas! That’s the best way to learn.


See also:

Hi Nina. Thanks for the info about cache. Didn’t know there’s a performance benefit to using it. Nice.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms