Optimizing Your Coroutine!

Objective: Freeing up memory from your coroutines.

In a coroutine, the keyword “new” is instantiating the wait for seconds class. “Wait For Seconds” is a reference type, meaning it is creating memory allocation every time it runs. It is a garbage collection that must be cleaned up before the next frame can process every single iteration.

A more optimal way to handle this is if we can actually cache this reference “new Wait For Seconds.”

Create a Wait For Seconds variable that is used only in the coroutine.

Alternatively you can set the variable in the void start method and use a variable for the time.

Now insert the new variable in to the coroutine.

This removes all the allocated memory from your coroutine. As always, don’t be afraid to experiment your code, and I’ll see you in the next tutorial!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store