Get component is probably the most widely used way for components and scripts to communicate in Unity. However, if you’re constantly making Get Component calls within the Update function does it affect the performance of the game or app? The short answer, of coz (course)!
Take the following example, though not wrong it can prove inefficient as calls to Get Component will be made every frame. For some functions we may want calls every frame, but for more complex tasks this can be taxing on the efficiency of our game or app. Imagine this happening for as long as our game is running. When we make Get Component calls this is a function that actually returns a result. What can we do to make this more efficient? Great you asked!
Storing and reusing these references can boost our efficiency. This is referred to as “caching” which allows us to store data so future requests for that same data will be faster. The data stored in cache can be anything that resulted in an earlier function return or computation. When we want a repeated result, instead of calling and returning the result from repeated function calls we can call it once, store it in cache, and access that cache at a later point in time.
Here’s an example of making the same function call once every frame compared to caching it once and grabbing it from our saved cache for future use.
In the following examples the two are identical in terms of function. Both create references to the mesh renderer storing it in a variable then passing the variable into a function, however the first example (Fig 1) our calls are made in the Update function which is constantly called every frame.
The second example (Fig 2) calls Get Component just once in our Start function. The result of the function is cached and can be reused in our Update function without any additional calls to Get Component. Tell me that’s not cool! This approach is useful for cases where we make frequent calls to functions returning a result which will massively boost the efficiency of our game or app. Till the next time!