简体   繁体   English

C#中迭代器的内存使用情况

[英]Memory usage of iterators in C#

What is the impact on memory usage of using lots of iterators in C#? 在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 ? 让我们假设一个执行数千个foreach循环的程序 - 每个循环是否通过调用GetEnumerator在堆上分配一个临时对象? Does the CLR perform any kind of optimization (eg stack allocation of IEnumerator objects)? CLR是否执行任何类型的优化(例如, IEnumerator对象的堆栈分配)? 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. 如果你正在做成千上万的foreach循环,大概是你在这些循环中做实际的工作 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. 请注意,在数组上使用foreach (在编译时称为数组),无论如何都不使用IEnumerable<T> - 它使用直接索引。 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). 编译器通常可以将foreach循环优化为一个简单的循环,这只需要堆栈(或处理器寄存器)中的索引变量。

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. 您可以创建数百万个而不会产生明显的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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