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.

--

--

--

Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

C libraries — An early project structure designed for portability, extensibility, and performance.

Specter Finance — #SpecterUpdates_01

Configuring HTTPD Server on Docker Container

Learn to Python: Codewars 6kyu question

Learn To Code. It Can Empower You.

Magento SaaS Performance

AWS Certified Solutions Architect Associate Exam Preparation

Help! I’m a CEO and already in Technical Debt!

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
Simon Leen

Simon Leen

Developer

More from Medium

Saving Data in Unity3D Using Files

How to setup Git for a Unity project

Hand Detection in 3D Space

An exercise with MinIO & Imgproxy