0

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:

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?

Community
  • 1
  • 1
Callum Linington
  • 14,213
  • 12
  • 75
  • 154
  • It is always larger and always slower and you cannot compare IEnumerable to IList. Whether that actually affects your program is never that straight-forward, in general only 10% of the code in a program matters to perf. And the state machine usually only takes ~9 fields and you are not going have dozens of them lying around. If you have no idea whether your iterator falls in that 10% bracket then you must use a profiler. – Hans Passant May 28 '16 at 11:26
  • What is "It" referring to ? @HansPassant – Callum Linington May 28 '16 at 11:55
  • An iterator, the subject of your question. – Hans Passant May 28 '16 at 11:57
  • So I am right in my observations, interesting. – Callum Linington May 28 '16 at 14:18

0 Answers0