简体   繁体   English

这两种使用foreach的方式有区别吗?

[英]Is there a difference between these two ways of using foreach?

Is there a difference between the two code snippets shown below? 下面显示的两个代码段之间有区别吗?

  1. Property loaded into variable before the foreach clause. foreach子句之前将属性加载到变量中。

     var someCollection = someClass.Collection; foreach (var elem in someCollection) { // Do something } 
  2. Property accessed inline within the foreach clause. foreach子句中内联访问的属性。

     foreach (var elem in someClass.Collection) { // Do something } 

Is second variant less optimized and if so, why? 第二种变体是不是很优化,如果是这样,为什么?

There is no difference between the two approaches, optimization- or performance-wise. 两种方法之间没有区别 ,优化或性能方面。 To prove this, I have created a brief example similar to yours: 为了证明这一点,我创建了一个类似于你的简短示例:

public class C {
    public void A() {
        foreach (var item in SomeClass.Collection) {}
    }

    public void B() {
        var someCollection = SomeClass.Collection;
        foreach (var item in someCollection) {}
    }   
}

public static class SomeClass {
    public static List<string> Collection { get; set; }
}

When compiled using the Roslyn .NET compiler version 2.9.0, both methods A and B result in the very same intermediate code as shown below ( reference ). 使用Roslyn .NET编译器版本2.9.0进行编译时 ,方法AB产生完全相同的中间代码,如下所示( 参考 )。

Method Body of A and B 方法体AB

List<string>.Enumerator enumerator = SomeClass.Collection.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        string current = enumerator.Current;
    }
}
finally
{
    ((IDisposable)enumerator).Dispose();
}

There is no difference in performance or optimization. 性能或优化没有区别。 The only difference is that you have one more variable in your code, which holds a reference (an address, a "pointer") to your collection. 唯一的区别是你的代码中还有一个变量,它包含你的集合的引用(一个地址,一个“指针”)。

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

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