- Home /
Why do my Coroutines allocate memory when they execute?
I'm optimizing GC on a project compiled with Unity 5.3 Win 8 64bit which uses Coroutines like this:
public override void Start() {
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine() {
while (true) {
yield return 0;
}
}
According to the profiler, the example above allocates 37B (shallow profiling) 20B (deep profiling) of memory on every frame:
I couldn't find much info about this - is it a known issue? Does it happen in production and/or mobile builds? Is it worth avoiding Coroutines when ram or GC spikes are a concern?
And could this be related to the bug in Mono which causes unnecessary boxing when iterating through a List using foreach (as opposed to for int i;;)? I wonder if both are calling MoveNext() at some level.
Answer by Bunny83 · Dec 01, 2015 at 01:47 PM
Don't yield "0". An IEnumerator is based on the type "object". If you want to wait one frame return null. The value 0 is an integer which need to be boxed on the heap so it can be returned as object.
astounding factoid! this is what the "reward" button is for :)
Yes! This fixes it. I'll replace "yield return 0" with "yield return null". Another thing that works is:
WaitForSeconds nextframe = new WaitForSeconds(0);
IEnumerator $$anonymous$$yCoroutine() {
while (true) {
yield return nextframe;
}
}
nextframe! whatever will they think of next?
Your answer
Follow this Question
Related Questions
Large Cubemap Optimization 0 Answers
UI-based game memory and performance issue. 1 Answer
Sprite-based animation - mobile memory issue 0 Answers
lightmap vs normals 2 Answers