Using Iterators in C #

What is the impact on memory usage of a large number of iterators in C #? Suppose a program that executes thousands of foreach loops - each loop allocates a temporary object on the heap through a call to GetEnumerator ? Does the CLR perform any optimization (for example, allocating a stack of IEnumerator objects)? Or is this just not an important enough question to even worry about?

+6
performance optimization iterator c # ienumerable
source share
2 answers

It is just not important enough to worry in most cases. As Eric points out, there may be some cases where this is important, but they are quite small and far from my experience.

If you do hundreds of thousands of foreach loops, presumably you are doing the actual work in these loops. This will almost certainly be much more important than the iterators themselves.

Note that using foreach over an array (known to be an array at compile time, that is) does not use IEnumerable<T> in any case - it uses direct indexing. I would not change my code based on this, though.

As before, if you are concerned about performance, you need to measure and profile it. Bottlenecks are almost never expected.

+13
source share

Often, the compiler can optimize the foreach loop into a simple loop that requires only an index variable in the stack (or in the processor register).

If the iterator is still in use, most of them are structures, so they just pop out on the stack, not on the heap.

The few iterators that are classes are still quite small and fast. You can create millions of them without noticeable impact.

+2
source share

All Articles