Which for loop format to use?

When I am writing code, I sometimes wonder which format is faster;

The old fashioned use of an incrementing variable: i

or

A foreach loop?

Answers


Neither is "faster" you need to use the right tool for the job, sometimes for is faster sometimes foreach is faster.

"micro optimizations" like you are taking about are so insignificant that you will NEVER recover the time in speed up than you will compared to the amount of extra time you took implementing it.

If your program is slow use a profiler on it and find where the real problem is.


Please refer the following links, which might give you more idea about for and foeach.

for: http://msdn.microsoft.com/en-us/library/ch45axte.aspx

foreach: http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx

for vs foreach

http://social.msdn.microsoft.com/Forums/vstudio/en-US/4ede2e82-e3df-44dc-a863-a871925c5cc5/foreach-or-for-loop-to-improve-performance-c-code http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx


Need Your Help

CDO message: text attachment gets corrupted

email attachment cdo.message

I'm creating an email message using CDO object (and VB6, but that doesn't really matter).

Rendering image to Bitmap from 3D model from model3dgroup fail

c# wpf bitmap helix-3d-toolkit

I am using C# WPF and I'm trying to render a 2D view from a 3D model that I could use as a preview image for my ui items.