Code Optimization- Game Dev Series 145
Objective: some tips of optimizine scripts for a better game performance.
In this article, we will focus on some tips of optimizing scripts to get a same result with lower amounts of garbage collecation allocation.
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.
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:
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.
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
Arraytakes more resources when calling. Try
stringtakes lots of resources than you thought!
- When creating a custom
classwith less than 5 variables, try to create it with
class, which is faster and more efficient.