- Home /
Does a coroutine do all its work during one frame?
Sounds like a yes or no question, but I did want to extrapolate. It's more of an optimization question.
If yes, what would be a good way to spread calculations out across a few different frames to reduce performance spiking?
Should I place a `yield return new WaitForEndOfFrame();` between calculations? Does this do what I want? Is there another more proper way?
The reason I ask is, while I'm not doing anything particularly heavy, I do have a lot happening that I think is currently all being calculated in one frame, leading to uneven performance.
Example:
Will this,
IEnumerator Test_Coroutine()
{
var1 += 1;
yield return new WaitForEndOfFrame();
var2 += 1;
yield return new WaitForEndOfFrame();
var3 += 1;
yield return new WaitForEndOfFrame();
var4 += 1;
}
...result in smoother performance than just running all 4 calculations in the same frame, or is this an incorrect use of WaitForEndOfFrame? (For the sake of the example, I'm well aware that adding 1 to a variable isn't a hard calculation. Pretend I'm doing something more advanced in place of these. :))
Thanks for any help. It's really just a clarification that I need, and hopefully it'll help anyone else with similar questions.
Answer by aldonaletto · Nov 18, 2012 at 02:07 AM
You could simply use yield return null instead: the coroutine stops at this instruction and resumes next frame in the following line. WaitForEndOfFrame does the same, but only after all cameras and GUI has been rendered - useful when getting screen snapshots.
A coroutine is a good way to span infrequent and time consuming pieces of code (usually loops) across several frames in order to reduce performance hiccups, as you already knew. But a compromise must be found: yielding after each iteration in a long loop will make the whole task take too much time. If you must create 1000 objects, for instance, yielding after each Instantiate would take 1000 frames - 33 seconds at 30 fps! If you yielded after each 10 objects, on the other hand, it would take only 3.3 seconds, and so on.
Your answer
![](https://koobas.hobune.stream/wayback/20220613084037im_/https://answers.unity.com/themes/thub/images/avi.jpg)