Basics of Optimization in Unity

Hernando Nieto Jaramillo
3 min readSep 29, 2021

Let’s say we put a cube in the scene and attach material which color will be modified in Update()

It could generate almost 300B of GC, not that much, but it can be improved

If we change the code like this

It will keep generating GC, why?

Because in Update, we are accesing material, that is a class, a reference type, each frame

Can color also cause GC? The answer is no
Because color is a struct, a value type

They’re on the stack and don’t require GC from the heap.

New in Color basically “initializes” a color variable in the Color struct, whereas a class (reference type, like Material) variable creates a reference in the heap that generates GC

Other examples of structs in Unity are Vector2 and Vector3

So, would the following example be desirable?

Although it uses struct objects and doesn’t generate GC, it is better to improve the code as much as possible, even more in the Update, it is, to make the code more optimal

In the code above, we are creating just 1 struct object and modifying only its x value, instead of creating 2 new structs each frame.


Use these code snippets for better revision in the profiler