Optimizing Coroutines
Objective: New isn’t always better. Cached returns.
In the previous post, we fixed an issue where Debug was causing some unwanted Garbage Collection. Unfortunately we have some but not nearly as much of the same with some Coroutines running as you can see in the image above. The biggest issue we have is within th Coroutine we call a new WaitForSeconds each time the Coroutine is called. This makes Unity create and allocate wasted memory allocation.
Fortunately there is a rather easy fix and though it doesn’t always clear the whole problem it does help. This is called Caching. Instead of creating a new WaitForSeconds each time the Coroutine is called, we can create a WaitForSeconds global variable and assign it in the Start method.
With that now created Unity doesn’t have to create new instances each call but rather uses the created and cached version as often as needed without giving up extra memory.
As you can see in the image above, using this cached version reduces the Coroutine GC allocation from 438B to 398B. Yes, I know what you’re thinking and yes that is such a small amount but all performance gained is still better performance and stability and over multiple scripts, calls and coroutines, these small bits could make a lot of difference.