I'm not sure that this has a huge effect on modern day computers.
However, it is interesting to know.
I've been reading these resources trying to find out if the over head of using the iterator state machine is larger than just returning a list. The emphasis is not on the ability to lazy load, in my example it makes no odds on when it is evaluated.
Resoures:
- C# yield return performance
- When NOT to use yield (return)
- Is there ever a reason to not use 'yield return' when returning an IEnumerable?
- https://blogs.msdn.microsoft.com/wesdyer/2007/03/23/all-about-iterators/
- https://coding.abel.nu/2011/12/return-ienumerable-with-yield-return/
- Is 'yield return' slower than "old school" return?
Now the last resource is probably the closest.
It comes down to this if you know length of list is a constant is:
Is the footprint of IEnumerable<T>
state machine >
List<T>
So:
public void IEnumerable<CustomClass> GetCustoms(string input)
{
foreach (var ch in input.ToCharArray())
yield return new CustomClass(ch);
}
does the state machine create a larger overhead than:
public void IEnumerable<CustomClass> GetCustoms(string input)
{
var result = new List<CustomClass>(input.Length);
foreach(var ch in input.ToCharArray())
result.Add(new CustomClass(ch));
return result;
}
Obviously this is a contrived example. but it illustrates the point.
I can imagine, that if there was a lot of preprocessing happening before the iteration in the methods, that the state machine would contain all that pre processing overhead.
Logic would say that the allocation of List
memory is far less than the allocation IEnumerable
state machine memory.
Obviouosly the bigger the enumeration, the more it starts to flip the other way and the IEnumerable
state machine becomes a smaller foot print.
Are these observations correct?