What I’ve noticed myself is that when starting IEnumerators, memory is allocated, initially I used a bazillion of IEnumerators in my project that started and stopped quite frequent and I noticed it did have an impact on the framerate, so obviously I rewrote so that the ones that were restarted most frequent to the Update() / LateUpdate() methods.
I don’t think you have to worry about it though since I can’t imagine the memory allocations beeing extremely great, as said for my example I just had really lots of them all the time. My recommendation would be to use the yield command for now, and in case you notice a loss of performance check the profiler to see what is causing it.
Edit
I’m not completely sure but I think the yield command work similar to the “Invoke” method, so it’s probably not free either, I might be wrong though!
// Original code from - http://forum.unity3d.com/threads/c-coroutine-waitforseconds-garbage-collection-tip.224878/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class YieldFunc
{
class FloatComparer : IEqualityComparer<float>
{
bool IEqualityComparer<float>.Equals (float x, float y)
{
return x == y;
}
int IEqualityComparer<float>.GetHashCode (float obj)
{
return obj.GetHashCode();
}
}
static Dictionary<float, WaitForSeconds> _timeInterval = new Dictionary<float, WaitForSeconds>(100, new FloatComparer());
public static WaitForEndOfFrame EndOfFrame = new WaitForEndOfFrame();
public static WaitForFixedUpdate FixedUpdate = new WaitForFixedUpdate();
public static WaitForSeconds WaitForSeconds(float seconds)
{
if (SkipWaiting) return null;
WaitForSeconds wfs;
if(!_timeInterval.TryGetValue(seconds, out wfs))
_timeInterval.Add(seconds, wfs = new WaitForSeconds(seconds));
return wfs;
}
public static bool SkipWaiting = false;
}
Just copy paste it into your project. Usage is as simple as:
IEnumerator DoSomething()
{
for (int i = 0; i < 10; i++)
yield return YieldFunc.WaitForSeconds (1f);
yield return YieldFunc.EndOfFrame;
yield return YieldFunc.FixedUpdate;
}
This little snippet is great because it will create YieldInstructions and cache them for later use, enabling you to reuse them throughout the project and eliminate unnecessary allocations. The float comparer will also ensure no allocation is made when comparing via dictionary.