更快的循环方法("for"和"foreach")? [英] A faster loop approach ('for' and 'foreach')?

查看:91
本文介绍了更快的循环方法("for"和"foreach")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题源于我在foreach循环中问上一个问题的原因.我有一个很大的字符串数组(例如成千上万个),我想遍历该数组,并且还可以根据特定条件进行分解,因此我需要最佳性能.

This question derives from the reason I asked my last question on foreach loops. I have a large string array (say in the thousands), and I want to iterate through the array and also be able to break out based on a certain condition, and I need optimal performance.

一些示例代码:

for(int i = 0; i < array.length && flag == true; i++){
    //Processing and set flag
}

//..or

foreach(string item in array){
    //processing...set flag
    if(!flag)
        break;
}

哪种方式会更便宜?

推荐答案

您始终可以对它们进行基准测试.使用Stopwatch并进行一千万次迭代,以查看迭代速度更快.

You can always benchmark them. Use a Stopwatch and iterate over, say, ten million iterations to see which goes faster.

不过,我认为您会发现两者几乎完全相同,因为JIT编译器将数组上的foreach优化为基本上为.

What I think you'll find, though, is that the two are nearly identical since the JIT compiler optimizes foreach on an array to basically a for.

flevine100 实际上是正确的,因为通常,对于GetEnumerator方法创建实现IEnumeratorIEnumerator<T>的新对象的类型,for的效率比>的略高.内存分配和方法调用开销);对于System.Collections.Generic中的大多数集合,情况并非如此,但是,由于它们使用值类型枚举器的显式IEnumerable实现(更不用说

flevine100 is actually right that in general a for is slightly more efficient than a foreach for types whose GetEnumerator methods create a new object implementing IEnumerator or IEnumerator<T> (due to the memory allocation and method call overhead); this is less the case for most of the collections in System.Collections.Generic, however, due to their explicit IEnumerable implementation using value type enumerators (not to mention that the foreach construct does not actually require an IEnumerable implementation in the first place).

对于数组来说,甚至更少,特别是因为它们是固定大小的,因此通过JIT编译器进行优化很容易.

It's even less the case for arrays specifically because they are fixed-size and therefore trivial to optimize by the JIT compiler.

这篇关于更快的循环方法("for"和"foreach")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆