440

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 loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.

I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.

What would be ideal is to have each scenario listed and the best solution for the same.

For example (just an example of how it should be):

  1. for iterating an array of 1000+ strings - for is better than foreach
  2. for iterating over IList (non generic) strings - foreach is better than for

A few references found on the web for the same:

  1. Original grand old article by Emmanuel Schanzer
  2. CodeProject FOREACH Vs. FOR
  3. Blog - To foreach or not to foreach, that is the question
  4. ASP.NET forum - NET 1.1 C# for vs foreach

[Edit]

Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.

7
  • 4
    The difference still exists. Arrays in particular should be just as fast under foreach, but for everything else, plain loops are faster. Of course, most of the time, this won't make a difference, and of course, a clever JIT compiler could in theory eliminate the difference.
    – jalf
    Dec 13, 2008 at 22:53
  • 2
    I see three solutions: (1) Write a compiler that enumerates in random order (2) rename "foreach" to "ForEachInStrictOrder (3) Rename ourselves to ~Ian perhaps Iain? Jan 23, 2009 at 9:58
  • 2
    In general for would be faster then foreach. However if you care you've probably got "other problems" which are of higher importance... Feb 17, 2009 at 17:04
  • 4
    Without context, I can't know exactly what you're doing, but what happens when you come across a partially filled array? Dec 22, 2009 at 15:18
  • 1
    See also stackoverflow.com/questions/1723855/…
    – Wim Coenen
    Dec 22, 2009 at 16:43

41 Answers 41

451

Patrick Smacchia blogged about this last month, with the following conclusions:

  • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).
17
  • 178
    However, never forget: "Premature optimization is the root of all evil."
    – Oorang
    May 29, 2009 at 4:53
  • 30
    @Hardwareguy: Once you know that for is almost imperceptably faster, why shouldn't you start using it in general? It doesn't take extra time.
    – DevinB
    Sep 3, 2009 at 13:06
  • 64
    @devinb, using "for" is harder than using "foreach" as it adds code, another variable, a condition you need to check, etc. How many times have you seen an off-by-one error in a "foreach" loop?
    – tster
    Dec 3, 2009 at 15:45
  • 52
    @Hardwareguy, let me see if I got this straight. It takes 5 times longer to loop through a list with foreach than it does to loop through an array with for, and you're calling that insignificant? That kind of a performance difference might matter for your application, and it might not, but I wouldn't just dismiss it out of hand. Dec 23, 2009 at 0:04
  • 61
    Reading through the blog post it looks like the tests were run in Debug and not Release so that might have a factor. Additionally the difference is specifically for just the loop overhead. It doesn't affect the time to execute the body of the loop at all which is most cases is much longer than the time it takes to move to the next element of the list. It's good information to know when you've identified that there clearly is a problem and you've measured the difference in your app specifically and there's a noticeable improvement but definitely not general advice to remove all foreachs.
    – Davy8
    May 27, 2010 at 13:26
188

First, a counter-claim to Dmitry's (now deleted) answer. For arrays, the C# compiler emits largely the same code for foreach as it would for an equivalent for loop. That explains why for this benchmark, the results are basically the same:

using System;
using System.Diagnostics;
using System.Linq;

class Test
{
    const int Size = 1000000;
    const int Iterations = 10000;

    static void Main()
    {
        double[] data = new double[Size];
        Random rng = new Random();
        for (int i=0; i < data.Length; i++)
        {
            data[i] = rng.NextDouble();
        }

        double correctSum = data.Sum();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j=0; j < data.Length; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in data)
            {
                sum += d;
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
    }
}

Results:

For loop: 16638
Foreach loop: 16529

Next, validation that Greg's point about the collection type being important - change the array to a List<double> in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still almost always prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is.

7
  • "change the array to a List<double> in the above, and you get radically different results" Very interesting, I hadn't thought about that
    – johnc
    Jan 23, 2009 at 10:12
  • 6
    Given the strange differences in results between my tests and other people's benchmarks, I think this is going to merit a blog post...
    – Jon Skeet
    Jan 23, 2009 at 10:19
  • 1
    Which do you almost always prefer between arrays and List<T>? Does readability trump micro-optimization in that case too?
    – JohnB
    May 27, 2010 at 16:18
  • 18
    @JohnB: Yup - I almost always prefer List<T> over arrays. The exceptions are char[] and byte[] which are more often treated as "chunks" of data rather than normal collections.
    – Jon Skeet
    May 27, 2010 at 16:38
  • 3
    @Adjit: I don't know whether I looked into that at the time (bear in mind this was over 13 years ago) - but I wouldn't be at all surprised to find that things have changed a lot in the meantime. Moral of the story: always measure.
    – Jon Skeet
    Jun 1, 2022 at 13:46
169

foreach loops demonstrate more specific intent than for loops.

Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection irrespective of its place in the collection. It also shows you aren't modifying the original collection (and throws an exception if you try to).

The other advantage of foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index.

However, if you need to use the index of an element, then of course you should be allowed to use a for loop. But if you don't need to use an index, having one is just cluttering your code.

There are no significant performance implications as far as I'm aware. At some stage in the future it might be easier to adapt code using foreach to run on multiple cores, but that's not something to worry about right now.

11
  • 30
    ctford: No it's not. The compiler certainly cannot reorder elements in foreach. foreach is not at all related to functional programming. It's totally an imperative paradigm of programming. You are mis-attributing things happening in TPL and PLINQ to foreach. Dec 22, 2009 at 15:53
  • 14
    @BlueTrin: It certainly does guarantee ordering (C# spec section 8.8.4 formally defines foreach as an equivalent of a while loop). I think I know @ctford is referring to. Task parallel library allows the underlying collection to provide elements in an arbitrary order (by calling .AsParallel on an enumerable). foreach doesn't do anything here and the body of the loop is executed on a single thread. The only thing that is parallelized is the generation of the sequence. Dec 22, 2009 at 16:11
  • 6
    Enumerable.Select has an overload that lets you obtain the index of the item, so even the need for an index does not mandate using for. See msdn.microsoft.com/en-us/library/bb534869.aspx
    – TrueWill
    Dec 22, 2009 at 18:16
  • 5
    ForEach is handy for readability and saving typing. Costs matter, though; changing 2 or 3 for-loops in a document designer UI that I made, from (for each obj in list) to (for i=0 to list.count-1) reduced response time from 2-3 sec per edit to about .5 sec per edit on a small document just looping thru a few hundred objects. Now for even huge documents, there is no increase in time to loop all. I have no idea how this happened. What I do know is that the alternative was a complicated scheme to only loop a subset of the objects. I'll take the 5 minute change any day! - not micro-optimisation.
    – FastAl
    Mar 31, 2011 at 13:37
  • 7
    @FastAl The difference between foreach and for performance for normal lists is fractions of a second for iterating over millions of items so your issue certainly wasn't directly related to foreach performance, at least not for a few hundred objects. Sounds like a broken enumerator implementation in whatever list you were using. Nov 26, 2017 at 1:38
55

It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ, etc. In general, stick with foreach.

Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.

2
  • So are you saying LinkedList<T> is leaner than List<T>? And if I'm always going to be using foreach (instead of for), I'm better off using LinkedList<T>?
    – JohnB
    May 26, 2010 at 20:00
  • 3
    @JohnB - not leaner; just different. For example, each node in a linked list has additional references that aren't needed for a flat array (which also underpins List<T>). It is more that it is cheaper to insert / remove. May 26, 2010 at 21:37
54

Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case.

Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop):

using System.Diagnostics;
//...
Stopwatch sw = new Stopwatch()
sw.Start()
for(int i = 0; i < 1000000;i ++)
{
    //do whatever it is you need to time
}
sw.Stop();
//print out sw.ElapsedMilliseconds

Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code

3
  • 14
    But you can't compare performance of for and foreach. They are supposed to be used in different circumstances. Dec 22, 2009 at 15:11
  • 8
    I agree with you Michael, you shouldn't choose which one to use based on performance - you should choose the one that makes the most sense! But if your boss says "Don't use for because it's slower than foreach" then this is the only way to convince him that the difference is negligible Dec 22, 2009 at 15:19
  • "(This might be hard without a for loop)" Or you can use a while loop.
    – jonescb
    Dec 22, 2009 at 18:42
39

My guess is that it will probably not be significant in 99% of the cases, so why would you choose the faster instead of the most appropriate (as in easiest to understand/maintain)?

1
  • 6
    @klew, If you actually profile your code you wouldn't have to guess which 20% need to be as fast as possible. You would probably also find out that the actual number of loops which need to be fast is much lower. Furthermore, are you really saying that the act of looping is where you spend your time, as opposed to what you actually do in that loop?
    – tster
    Dec 3, 2009 at 15:47
34

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.

3
  • How does recursion compare to for loops and foreach loops performance-wise?
    – JohnB
    May 27, 2010 at 5:18
  • It depends. If you use tail-recursion and your compiler is smart enough to notice, it can be identical. OTOH: If it doesn't and you do something stupid like pass a lot of unnessecary (unchanging) data as parameters or declare big structures on the stack as locals, it can be really really slow (or even run out of RAM).
    – T.E.D.
    May 27, 2010 at 12:55
  • Ahhh. I see why you asked that now. This answer went to a totally different question. For some bizzare reason Jonathan Sampson merged the two yesterday. He really shouldn't have done that. The merged answers will make no sense here whatsoever.
    – T.E.D.
    May 27, 2010 at 13:02
32

There is unlikely to be a huge performance difference between the two. As always, when faced with a "which is faster?" question, you should always think "I can measure this."

Write two loops that do the same thing in the body of the loop, execute and time them both, and see what the difference in speed is. Do this with both an almost-empty body, and a loop body similar to what you'll actually be doing. Also try it with the collection type that you're using, because different types of collections can have different performance characteristics.

21

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
14

you can read about it in Deep .NET - part 1 Iteration

it's cover the results (without the first initialization) from .NET source code all the way to the disassembly.

for example - Array Iteration with a foreach loop: enter image description here

and - list iteration with foreach loop: enter image description here

and the end results: enter image description here

enter image description here

11

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.

1
  • "Better" is debateable: It is slower and the dnspy debugger won't break into a C# foreach (although VS2017 debugger will). Sometimes more readable but if you support languages without it, it can be annoying.
    – Zeek2
    Jul 26, 2018 at 9:21
10

This should save you:

public IEnumerator<int> For(int start, int end, int step) {
    int n = start;
    while (n <= end) {
        yield n;
        n += step;
    }
}

Use:

foreach (int n in For(1, 200, 4)) {
    Console.WriteLine(n);
}

For greater win, you may take three delegates as parameters.

1
  • 1
    One tiny difference is that a for loop is usually written to exclude the end of the range (e.g. 0 <= i < 10). Parallel.For also does that to keep it easily interchangeable with a common for loop.
    – vgru
    Jul 24, 2014 at 19:42
9

The differences in speed in a for- and a foreach-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.

What hasn't been said so far is that when a foreach loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach loop - it will generate the best loop for you when it gets compiled. It's more readable too.

Another key advantage with the foreach loop is that if your collection implementation changes (from an int array to a List<int> for example) then your foreach loop won't require any code changes:

foreach (int i in myCollection)

The above is the same no matter what type your collection is, whereas in your for loop, the following will not build if you changed myCollection from an array to a List:

for (int i = 0; i < myCollection.Length, i++)
9

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).

8

"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
7

Every language construct has an appropriate time and place for usage. There is a reason the C# language has a four separate iteration statements - each is there for a specific purpose, and has an appropriate use.

I recommend sitting down with your boss and trying to rationally explain why a for loop has a purpose. There are times when a for iteration block more clearly describes an algorithm than a foreach iteration. When this is true, it is appropriate to use them.

I'd also point out to your boss - Performance is not, and should not be an issue in any practical way - it's more a matter of expression the algorithm in a succinct, meaningful, maintainable manner. Micro-optimizations like this miss the point of performance optimization completely, since any real performance benefit will come from algorithmic redesign and refactoring, not loop restructuring.

If, after a rational discussion, there is still this authoritarian view, it is up to you as to how to proceed. Personally, I would not be happy working in an environment where rational thought is discouraged, and would consider moving to another position under a different employer. However, I strongly recommend discussion prior to getting upset - there may just be a simple misunderstanding in place.

7

It probably depends on the type of collection you are enumerating and the implementation of its indexer. In general though, using foreach is likely to be a better approach.

Also, it'll work with any IEnumerable - not just things with indexers.

6

Whether for is faster than foreach is really besides the point. I seriously doubt that choosing one over the other will make a significant impact on your performance.

The best way to optimize your application is through profiling of the actual code. That will pinpoint the methods that account for the most work/time. Optimize those first. If performance is still not acceptable, repeat the procedure.

As a general rule I would recommend to stay away from micro optimizations as they will rarely yield any significant gains. Only exception is when optimizing identified hot paths (i.e. if your profiling identifies a few highly used methods, it may make sense to optimize these extensively).

7
  • 1
    If the only kind of optimization I needed to do in the projects I work on were micro optimizations, I would a happy camper. Sadly, this is never the case. Dec 22, 2009 at 15:43
  • 3
    for is marginally faster than foreach. I'd seriously object to this statement. That totally depends on the underlying collection. If a linked list class provides an indexer with an integer parameter, I would expect using a for loop on it to be O(n^2) while foreach is expected to be O(n). Dec 22, 2009 at 16:17
  • 1
    @Merhdad: Actually that is a good point. I was just thinking about the regular case of indexing a list (i.e. array). I'll reword to reflect that. Thanks. Dec 22, 2009 at 16:50
  • 1
    @Mehrdad Afshari: Indexing a collection by integer may be much slower than enumerating over it. But you are actually comparing using for and an indexer lookup to using foreach by itself. I think @Brian Rasmussen's answer is correct that, aside from any use with a collection, for will always be slightly faster than foreach. However, for plus a collection lookup will always be slower than foreach by itself. Dec 22, 2009 at 16:52
  • 1
    @Daniel: Either you have a plain array, for which both will generate identical code, or there's an indexer involved when you use for statement. Plain for loop with an integer control variable is not comparable to foreach, so that's out. I understand what @Brian means and it's correct as you say but the answer can be misleading. Re: your last point: no, actually, for over List<T> is still faster than foreach. Dec 22, 2009 at 16:59
5

It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).

5

A powerful and precise way to measure time is by using the BenchmarkDotNet library.

In the following sample, I did a loop on 1,000,000,000 integer records on for/foreach and measured it with BenchmarkDotNet:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

public class Program
{
    public static void Main()
    {
        BenchmarkRunner.Run<LoopsBenchmarks>();
    }
}

[MemoryDiagnoser]
public class LoopsBenchmarks
{
    private List<int> arr = Enumerable.Range(1, 1_000_000_000).ToList();

    [Benchmark]
    public void For()
    {
        for (int i = 0; i < arr.Count; i++)
        {
            int item = arr[i];
        }
    }

    [Benchmark]
    public void Foreach()
    {
        foreach (int item in arr)
        {
        }
    }
}

And here are the results:

enter image description here

Conclusion

In the example above we can see that for loop is slightly faster than foreach loop for lists. We can also see that both use the same memory allocation.

2
  • I think you need int item = arr[i]; in the body of the for to make it a fair comparison, and it'd be good to do some work (e.g. sum += item;) in the body of both loops. Since BenchmarkDotNet makes it easy to do so, it'd be interesting to compare runs between .NET Framework and Core. Another benchmark to add might be to see if caching the collection size in a variable for the loop condition (i.e. int length = arr.Length; for (int i = 0; i < length; i++) { }) yields appreciable improvement; perhaps that's more significant for non-Array implementations of IList<>. Oct 11, 2022 at 5:55
  • 1
    This matches a benchmark I did. Thanks for giving an updated answer, because the 14 year old accepted answer is no longer correct in my opinion. I hope we can push this answer up the ranks!
    – Tim Cooper
    Jan 18, 2023 at 5:34
4

The two will run almost exactly the same way. Write some code to use both, then show him the IL. It should show comparable computations, meaning no difference in performance.

2
  • The compiler recognises foreach loops used on arrays/ILists etc and changes them to for loops. Dec 22, 2009 at 15:13
  • 4
    Show him lines of unintelligble proof that it is OK and ask for his proof that it is not OK.
    – cjk
    Dec 22, 2009 at 15:45
4

In most cases there's really no difference.

Typically you always have to use foreach when you don't have an explicit numerical index, and you always have to use for when you don't actually have an iterable collection (e.g. iterating over a two-dimensional array grid in an upper triangle). There are some cases where you have a choice.

One could argue that for loops can be a little more difficult to maintain if magic numbers start to appear in the code. You should be right to be annoyed at not being able to use a for loop and have to build a collection or use a lambda to build a subcollection instead just because for loops have been banned.

4

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.

1
  • Essential quote form the article you link to: "...if you are planning to write high performance code that is not for collections, use for loop. Even for collections, foreach may look handy when using, but it's not that efficient. "
    – NickFitz
    Dec 22, 2009 at 16:54
4

You can really screw with his head and go for an IQueryable .foreach closure instead:

myList.ForEach(c => Console.WriteLine(c.ToString());
2
  • 5
    I'd replace your line of code with myList.ForEach(Console.WriteLine). Dec 22, 2009 at 16:16
  • LINQ ForEach use for (int i = 0; i < _size; i++) but for every iteration it also checks that the collection has not changed. Nov 13, 2022 at 19:22
3

for has more simple logic to implement so it's faster than foreach.

0
3

Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.

If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.

3

Jeffrey Richter talked the performance difference between for and foreach on a recent podcast: http://pixel8.infragistics.com/shows/everything.aspx#Episode:9317

3

I did test it a while ago, with the result that a for loop is much faster than a foreach loop. The cause is simple, the foreach loop first needs to instantiate an IEnumerator for the collection.

3
  • 4
    Not with an array it doesn't. Compile it and look at the IL :) (It also depends on the collection. IIRC, List<T> uses a value type for the enumerator.)
    – Jon Skeet
    Dec 13, 2008 at 20:34
  • Why would one allocation be expensive? In managed .NET, allocations are practically free aren't they, since all that is done is that the pointer is incremented in the managed heap, there is little if any fragmentation in most cases. Dec 13, 2008 at 20:48
  • 1
    not just one allocation, also all the method-calling overhead of MoveNext() and get_Current() for each iteration.
    – Lucas
    May 19, 2009 at 19:47
3

I found the foreach loop which iterating through a List faster. See my test results below. In the code below I iterate an array of size 100, 10000 and 100000 separately using for and foreach loop to measure the time.

enter image description here

private static void MeasureTime()
    {
        var array = new int[10000];
        var list = array.ToList();
        Console.WriteLine("Array size: {0}", array.Length);

        Console.WriteLine("Array For loop ......");
        var stopWatch = Stopwatch.StartNew();
        for (int i = 0; i < array.Length; i++)
        {
            Thread.Sleep(1);
        }
        stopWatch.Stop();
        Console.WriteLine("Time take to run the for loop is {0} millisecond", stopWatch.ElapsedMilliseconds);

        Console.WriteLine(" ");
        Console.WriteLine("Array Foreach loop ......");
        var stopWatch1 = Stopwatch.StartNew();
        foreach (var item in array)
        {
            Thread.Sleep(1);
        }
        stopWatch1.Stop();
        Console.WriteLine("Time take to run the foreach loop is {0} millisecond", stopWatch1.ElapsedMilliseconds);

        Console.WriteLine(" ");
        Console.WriteLine("List For loop ......");
        var stopWatch2 = Stopwatch.StartNew();
        for (int i = 0; i < list.Count; i++)
        {
            Thread.Sleep(1);
        }
        stopWatch2.Stop();
        Console.WriteLine("Time take to run the for loop is {0} millisecond", stopWatch2.ElapsedMilliseconds);

        Console.WriteLine(" ");
        Console.WriteLine("List Foreach loop ......");
        var stopWatch3 = Stopwatch.StartNew();
        foreach (var item in list)
        {
            Thread.Sleep(1);
        }
        stopWatch3.Stop();
        Console.WriteLine("Time take to run the foreach loop is {0} millisecond", stopWatch3.ElapsedMilliseconds);
    }

UPDATED

After @jgauffin suggestion I used @johnskeet code and found that the for loop with array is faster than following,

  • Foreach loop with array.
  • For loop with list.
  • Foreach loop with list.

See my test results and code below,

enter image description here

private static void MeasureNewTime()
    {
        var data = new double[Size];
        var rng = new Random();
        for (int i = 0; i < data.Length; i++)
        {
            data[i] = rng.NextDouble();
        }
        Console.WriteLine("Lenght of array: {0}", data.Length);
        Console.WriteLine("No. of iteration: {0}", Iterations);
        Console.WriteLine(" ");
        double correctSum = data.Sum();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i = 0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j = 0; j < data.Length; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum - correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop with Array: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (var i = 0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in data)
            {
                sum += d;
            }
            if (Math.Abs(sum - correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop with Array: {0}", sw.ElapsedMilliseconds);
        Console.WriteLine(" ");

        var dataList = data.ToList();
        sw = Stopwatch.StartNew();
        for (int i = 0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j = 0; j < dataList.Count; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum - correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop with List: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i = 0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in dataList)
            {
                sum += d;
            }
            if (Math.Abs(sum - correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop with List: {0}", sw.ElapsedMilliseconds);
    }
2
  • 4
    This is a very poor test. a) you do too few iterations to get a conclusive answer b) That Thread.Sleep will not really wait one millisecond. Use the same method as Jon Skeet did in his answer.
    – jgauffin
    Jun 12, 2014 at 5:51
  • 1
    99.99% of the time is definately spent in the thread.sleep (which makes no guarantees of how fast it will return except it won't before at least that time). Looping is very fast and sleeping is very slow, you don't use the later to test the former. Apr 20, 2015 at 12:02
2

I wouldn't expect anyone to find a "huge" performance difference between the two.

I guess the answer depends on the whether the collection you are trying to access has a faster indexer access implementation or a faster IEnumerator access implementation. Since IEnumerator often uses the indexer and just holds a copy of the current index position, I would expect enumerator access to be at least as slow or slower than direct index access, but not by much.

Of course this answer doesn't account for any optimizations the compiler may implement.

2
  • The C# compiler does very little optimisation, it really leaves that up to the JITter.
    – ljs
    Jan 25, 2009 at 0:24
  • Well, the JITter is a compiler... Right?
    – JohannesH
    Jan 30, 2009 at 5:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.