0

Possible Duplicate:
For vs Foreach loop in C#

What is the major difference between 'for each' and 'for' loops in .NET? Is there any performance gain while comparing these two? Which one gives a better performance/faster/memory management?

Community
  • 1
  • 1
kbvishnu
  • 12,180
  • 17
  • 64
  • 97
  • I think there's some good reading on this already available....I recently had the same questions myself. http://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c-sharp http://blogs.msdn.com/b/brada/archive/2004/04/29/123105.aspx http://msmvps.com/blogs/jon_skeet/archive/2009/01/29/for-vs-foreach-on-arrays-and-lists.aspx The conclusion that I came up with is that it really depends on what you're using them for. – Brian Snow Jan 13 '12 at 06:35
  • I am sorry I searched a lot using difference between For and For Each, but the results are based on Ruby,Java etc. I didn't find it for .net :( – kbvishnu Jan 13 '12 at 07:03
  • dont forget to mark answer as accpeted if you got the info you want – Pranay Rana Jan 18 '12 at 07:05

1 Answers1

2

See The Code Project article foreach vs. for (C#)*.

foreach is thinking about everything as a collection and is treating them as a collection. That will also reduce the performance of the work.

To write high performance code that is not for collections, use a for loop.

Even for collections, foreach may look handy when using, but it's not that efficient. Therefore, I strongly recommend everyone to use a for loop rather than foreach at any stage.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pranay Rana
  • 164,177
  • 33
  • 228
  • 256
  • Is there any benchmark for the loop thing available? i am to busy to do it my self right now – Grrbrr404 Jan 13 '12 at 06:36
  • @Grrbrr404 - Just read out that article and the other answer on stack overflow you will get idea what to use that what i can suggest you – Pranay Rana Jan 13 '12 at 06:38