Imagine that we have the following methods (pseudo C#):
static IEnumerable<T> Iterator<T>()
{
switch (SomeCondition)
{
case CaseA:
yield return default(T);
case CaseB:
yield return default(T);
yield return default(T);
case CaseC:
yield return default(T);
default:
break;
}
}
static IEnumerable<T> Array<T>()
{
switch (SomeCondition)
{
case CaseA:
return new[] { default(T) };
case CaseB:
return new[] { default(T), default(T) };
case CaseC:
return new[] { default(T) };
default:
break;
}
}
Which one will consume less memory (and less GC cycles) if we have many calls to similar like this methods? Does it make sense to write your own Enumerable/Enumerator in order to implement this kind of Enumerable.Once() scenario?
This one is faster than both the others:
But it really isn’t going to matter much.