Code Optimization- Game Dev Series 145

S.J. Jason Liu
3 min readJan 3, 2022

--

Objective: some tips of optimizine scripts for a better game performance.

Photo by Florian Olivo on Unsplash

In this article, we will focus on some tips of optimizing scripts to get a same result with lower amounts of garbage collecation allocation.

Cache GetComponent

GetComponent() would be a major problem when using it in Update(), which would create lots of garbage collection on every frame.
In this situation, the best way to solve this is cacheing GetComponent() in Start() with a variable instead of calling it in Update().

Here is an example:
In this script, we are changing the color of cube randomly on every frame.

When running the game, it would cause lots of garbage collection allocation.

338b at the first frame.

However, if we cache GetComponent() in Start(), and also cache the new color from a return type method instead of calculate in Update():

Here is the result after optimizing:

86b at the first frame.

As you can see, GC Alloc has successfully decrese from 338bit to 86bit. And this is only a simple color changing function on a basic cube. Imagine that you have a more complex game and keep causing laggy due to the calling of GetComponent() during every frame.

Cache WaitForSeconds

There is another example to optimize your script that is WaitForSeconds() in coroutine. For a common use, we always call a coroutine by using:

yield return new WaitForSeconds();

However, this can also be cached as a variable to save memories.
Here is an example of the difference:
Let’s create a coroutine that would process every 0.1 second, and name it NormalRoutin().

In the meantime, create another coroutine that doing the same function but with a variable that cache WaitForSeconds().

Let’s call both of these coroutine in Start(), then run the game to check Profiler.
And you should see the difference of GC Alloc between NormalRoutine and OptimizeRoutine.

More tips of saving memory

  • When creating RayCast through camera, instead of setting the ray with Camera.main, cache the camera as reference to prevent creating camera class multiple times.
  • Compare to List, Array takes more resources when calling. Try List!
  • string takes lots of resources than you thought!
  • When creating a custom class with less than 5 variables, try to create it with struct instead of class, which is faster and more efficient.

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.