Search code examples
c#unity-game-engineoptimizationgarbage-collectioncoroutine

Coroutine with while loop vs update with if condition


I noticed that every time I started a coroutine, it would create a tiny bit of garbage. I just wanted to know if looping the coroutine forever would be a valid way to avoid that.

Instead of this:

void Update()
{
    if (condition)
    {
        StartCoroutine(Example());
    }
}

IEnumerator Example()
{
    if (coroutineRunning)
    {
        yield break;
    }
    coroutineRunning = true;

    //Run code

    yield return new WaitForSeconds(0.1f);

    coroutineRunning = false;

    yield return null;
}

I could use this:

void Start()
{
    StartCoroutine(Example());
}

IEnumerator Example()
{
    while (true)
    {
        while (!condition)
        {
            yield return null;
        }

        //Run code

        yield return new WaitForSeconds(0.1f);
    }
}

I've already tested this and there is no GC allocation with looping the coroutine forever. I'm wondering if there is any downside to looping a coroutine like this.


Solution

  • A coroutine, being a parallel process to the main thread, should not create problems if it is always running, on the contrary, it will remove some work from the main tread and lighten it. So, yes, the second code is more efficient than the first. Consider that as you surely know, it is very important to take care of the performance of the code, but if there are performance problems, other aspects should be seen first.

    if you think my answer helped you, you can mark it as accepted and vote positively. I would very much appreciate it :)