- Home /
How often should I Yield the next frame in a coroutine for performance optimization?
So I have a Coroutine that performs some expensive operations like serialization, md5 hash and some compression algorithms.
Is is better for me to place my own "yield return null;" statement after every line in my script so I don't block the main thread or is the coroutine scheduler in Unity only running a few instructions each frame anyway and then yielding.
The caller of my coroutine is basically waiting for it to finish before proceeding.
I can place these yield statements in but my code becomes messy and very ugly.
IEnumerator KickItOff() { yield return StartCoroutine(ExpensiveOps()); }
IEnumerator ExpensiveOps() { serialize(); yield return null; // do I need these?
hash();
yield return null;
compress();
yield return null;
WWW post = new WWW("...",data);
yield return post;
}
How far is this suppose to go then? Every couple of instructions needs a yield so as not to block? Or just play it by ear?
I could always spawn my own threads to do some of these calculations and take care not to call the Unity API on that thread. Ideally I wouldn't have to do either.
Answer by Eric5h5 · Jun 08, 2010 at 04:23 AM
Unity doesn't interrupt coroutines until you use a yield; coroutines wouldn't work at all otherwise. I don't think those yield return nulls will really accomplish anything except to make the routine take a few extra frames longer to run...if you actually want to make coroutines work "sort of like threads", then you'd have to make the expensive routines themselves into coroutines and try yielding every few loops or something. That's pretty crude though. The only real way to make functions work like separate non-blocking threads is to use actual threads.
Threads are not coroutines! Eric is correct, if you need to use a thread, use it, don't substitute Coroutines in their place. :)
Answer by PaulUsul · Jun 08, 2010 at 10:44 AM
I have had the same problem, when doing heavy duty calculations. And coroutines do block and they do not call gc, so memory that is no longer referenced is not cleaned. So I usually call Wait For End Of Framme at the end of a "for" for-example. But I have only ever needed it where calculations took minutes. It really depends on whether you want frames or speedy results.
Your answer
Follow this Question
Related Questions
How to set timer for WWW helper? 1 Answer
Execution manner of co routine 2 Answers
Yield Wait for Seconds (A little help here) 2 Answers
Substracting Lives every n seconds on TriggerEnter 2 Answers