Tips for Code Optimization in Unity
In the last article, we explained one of the best tools Unity offers which is the Unity Profiler (Unity Profiler 101). The profiler helps you identify which part of your code is actually causing some performance issues. Let’s get to it.

GetComponent
Getting a component of any object is an essential part of unity development, usually you we get hold of a script or a Rigidbody or maybe the material of the object by GetComponent.
Sometimes you get the component without caching it first. For example, say you want to change the color of a cube. You might do the following in Update:

This will get the component of the object EVERY single frame to change the color of the object. If you check this using the profiler, you will see that this will cause some garbage collection and performance issues in the long run. One code may not do much harm, but imagine doing it more than once.

To help improve this, you must always cache your component then find it in Awake or Start and then do whatever you want with the component.

This caching of the component should also be done to variables, always cache to improve performance.
The New Keyword
The “New” keyword, just like getting components, is used to create new variables or Vectors. When used unwisely and very often, it could lead to performance issues.
Let’s say you want to change the position of an object using user input. You might use in update the following:

This will create a new vector each time the user presses the D key. What would be more optimal though, is caching a vector3 for position and then reusing the same vector, like this:

Yield Return New
Just like the new keyword for variables, IEnumerators require you to yield in order to execute the code inside it.
The yield return needs to create a “new” variable (WaitForSeconds() for example) each time it runs. When you have a lot of coroutines, this will definetly lead to garbage collection and performance issues. Instead of creating a new WaitForSeconds each time, cache it and reuse it just like variables. Here is how:

By caching the WaitForSeconds instead of creating a new one in the IEnumerator, you almost get rid of garbage collection created by this coroutine, and in the long run improve your application’s performance.