how many coroutines is too many

i’m coming to love coroutines.
i’m waiting for the other shoe to drop, but so far they’re filling my serialized-process needs really well.

i’m looking for some guidance tho:

  • what pitfalls may i run into using a lot of them ?
    currently i’ve got about 20, and many of them call each other.
    one problem i ran into was using a lambda (anonymous function) inside the body of a coroutine - the mono compiler would crash. but moving the lambda into its own function cleared things up.

  • what sort of performance overhead is here ?

i’m not looking for super obvious stuff, i more or less know what i’m doing.

tia!

The best way to gauge performance issues is to try and push the limits yourself and look at the profiler. I would recommend setting up a scene, cranking the number of coroutines up to an absurdly high number, and building the project to your target device, and see what happens. This is just general performance evaluation advice though! :slight_smile:

A more specific answer to your question is that the overhead on coroutines is very low. Starting a coroutine is essentially the same as instantiating an object in terms of overhead. Running a coroutine frame by frame shouldn’t be much more expensive than an Update function running in a MonoBehaviour.

A more specific answer to your quest is that the overhead on coroutines is very low. You should usually use coroutines for anything that you are not doing every frame (say once a second), or something that you do temporarily (like a 3 second speed boost). On a single frame, an Update() function will run significantly faster than a coroutine (up to 3-4x according to tests seen here: http://forum.unity3d.com/threads/coroutines-vs-update.67856/).

Overall you will save a lot of processing time if the coroutine only runs once every 10+ frames, or is only active temporarily. Also, when you create a coroutine you are actually instantiating an object, so there is a small overhead with that.

Long story short, you should be able to have hundreds, to thousands of coroutines running, depending what they are doing, how often they are doing it, and what your target device is. Hope this helps!

there is a limit when it slows down. I am running a coroutine that starts 722 coroutines that starts 1000 coroutines that each start 125 coroutines

I added an extra for loop i = 0 to 5000 with a yield return null; after each of the 722. basically it pauses and let’s everything catch up for 5000 iterations before starting the next set of coroutines.