简体   繁体   中英

Memory usage of iterators in C#

What is the impact on memory usage of using lots of iterators in C#? Let's assume a program that performs thousands of foreach loops -- does each loop allocate a temporary object on the heap via a call to GetEnumerator ? Does the CLR perform any kind of optimization (eg stack allocation of IEnumerator objects)? Or is this simply not a significant enough issue to even worry about?

It's simply not significant enough to worry about in most cases. As Eric points out, there may be some cases where it's important, but they're pretty few and far between in my experience.

If you're doing hundreds of thousands of foreach loops, presumably you're doing actual work within those loops. That will almost certainly be far more important than the iterators themselves.

Note that using foreach over an array (known to be an array at compile time, that is) doesn't use IEnumerable<T> anyway - it uses direct indexing. I wouldn't change my code based on this though.

As ever, if you're concerned about performance you need to measure it and profile it. Bottlenecks are almost never where you expect them to be.

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

If an iterator still is used, most of them are structures, so they are just allocated on the stack instead of on the heap.

The few iterator that are classes are still quite small and fast. You could create millions of them without a noticable impact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM