Coroutines performance question

Is running coroutines in separate scripts faster than running same coroutines in a single script? Say, there are 20 coroutines with http requests, for example. Would separation improve it or not?

Not.

Thank you for the answer. So, like, each time I do StartCoroutine() it’s a separate thread just for the exception that I can stop all coroutines of the used script at once. Right?

They aren’t threads at all. Coroutines are performed on the main thread, You can consider them just a convenience really.

You’ve opened my eyes to the problem now, thanks a lot, hippocoder. The thread may now be closed (heh, thread).

1 Like

Coroutines are not threads. The way I like to think about coroutines is each coroutine is like another Update method. It’s called in the same way as part of the update loop by Unity. You can yield different things to tell Unity when to call the coroutine again, like a WaitForSeconds object or WaitForFixedUpdate. Once you understand that they’re pretty easy to use.

1 Like

Thank you for the answer, UziMonkey. I know how to use coroutines, though I didn’t know what coroutines exactly are. I already did a research about it and also made a test script with Update() vs coroutine vs thread (using C# classes), the result was that coroutine turned out to be basically the same as Update(), just parallel, and the thread was wa-a-a-a-ay beyond both of them (is what I’ve been looking for). Bottom line is that I thought coroutines are actually what C# thread is, but I was so wrong :frowning:

Some of Unity API designed for coroutines is threaded, but the coroutine itself is not a thread, that is when execution comes to your script, it not on separate thread and is just like another Update().
In example UnityWebRequest is executed on a separate thread and when it completes, it triggers coroutine to continue execution next time all Update() are executed.

As for original question: it is completely irrelevant if coroutines were started from single or multiple scripts, the performance characteristics will be identical.

This is not a thread, this is a co-routine :roll_eyes:

Using coroutines have a perfmorance impact??

Writing code has performance impact in general :smile:. The question is usually how big that impact is.

1 Like

Hi friends
What do you think about using coroutines to implement AI games? For example, implementing each FSM state as a coroutone. Something like this article
https://www.behindthestone.de/612/unity-creating-a-simple-enemy-ai-with-coroutines/

Is this a good way to optimize performance on Mobile?
Or there are better solutions for optimal implementation of AI for mobile games!!?