In .NET, which loop runs faster, 'for' or 'foreach'?

前端 未结 30 1364
抹茶落季
抹茶落季 2020-11-22 04:25

In C#/VB.NET/.NET, which loop runs faster, for or foreach?

Ever since I read that a for loop works faster than a foreach

相关标签:
30条回答
  • 2020-11-22 04:28

    In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.

    Note that in the last case, you could do something like:

    foreach (int i in Enumerable.Range(1, 10))...
    

    But it certainly doesn't perform better, it actually has worse performance compared to a for.

    0 讨论(0)
  • 2020-11-22 04:28

    This has the same two answers as most "which is faster" questions:

    1) If you don't measure, you don't know.

    2) (Because...) It depends.

    It depends on how expensive the "MoveNext()" method is, relative to how expensive the "this[int index]" method is, for the type (or types) of IEnumerable that you will be iterating over.

    The "foreach" keyword is shorthand for a series of operations - it calls GetEnumerator() once on the IEnumerable, it calls MoveNext() once per iteration, it does some type checking, and so on. The thing most likely to impact performance measurements is the cost of MoveNext() since that gets invoked O(N) times. Maybe it's cheap, but maybe it's not.

    The "for" keyword looks more predictable, but inside most "for" loops you'll find something like "collection[index]". This looks like a simple array indexing operation, but it's actually a method call, whose cost depends entirely on the nature of the collection that you're iterating over. Probably it's cheap, but maybe it's not.

    If the collection's underlying structure is essentially a linked list, MoveNext is dirt-cheap, but the indexer might have O(N) cost, making the true cost of a "for" loop O(N*N).

    0 讨论(0)
  • 2020-11-22 04:29

    "Are there any arguments I could use to help me convince him the for loop is acceptable to use?"

    No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry.

    0 讨论(0)
  • 2020-11-22 04:29

    It seems a bit strange to totally forbid the use of something like a for loop.

    There's an interesting article here that covers a lot of the performance differences between the two loops.

    I would say personally I find foreach a bit more readable over for loops but you should use the best for the job at hand and not have to write extra long code to include a foreach loop if a for loop is more appropriate.

    0 讨论(0)
  • 2020-11-22 04:30

    There are very good reasons to prefer foreach loops over for loops. If you can use a foreach loop, your boss is right that you should.

    However, not every iteration is simply going through a list in order one by one. If he is forbidding for, yes that is wrong.

    If I were you, what I would do is turn all of your natural for loops into recursion. That'd teach him, and it's also a good mental exercise for you.

    0 讨论(0)
  • 2020-11-22 04:31

    Jeffrey Richter on TechEd 2005:

    "I have come to learn over the years the C# compiler is basically a liar to me." .. "It lies about many things." .. "Like when you do a foreach loop..." .. "...that is one little line of code that you write, but what the C# compiler spits out in order to do that it's phenomenal. It puts out a try/finally block in there, inside the finally block it casts your variable to an IDisposable interface, and if the cast suceeds it calls the Dispose method on it, inside the loop it calls the Current property and the MoveNext method repeatedly inside the loop, objects are being created underneath the covers. A lot of people use foreach because it's very easy coding, very easy to do.." .. "foreach is not very good in terms of performance, if you iterated over a collection instead by using square bracket notation, just doing index, that's just much faster, and it doesn't create any objects on the heap..."

    On-Demand Webcast: http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032292286&EventCategory=3&culture=en-US&CountryCode=US

    0 讨论(0)
提交回复
热议问题