We deal with collections and arrays almost everyday while writing programs and most of the time we need to iterate through all the elements present in an array or a collection. We normally use either for loop or foreachloop when it comes to iteration. From ease point of view while using these two types of looping we normally use foreach loop. So one question come to mind that which loop should I use. Should I use for loop or foreach loop? Before telling about my preference I would like to mention the differences between the two.
Both the techniques have advantages and disadvantages, the foreach loop is used mainly in arrays and collections but for statement can be used in any program. Tphe following code snippet helps you find the time difference in the execution of a for loop as well as a foreach loop.
|
Consider the following two looping declarations as given below.
for (long i = 0; i < 6000000; i++)
{
int j = 1;
}
foreach(long x in array) // Size of array is 6000000
{
int j = 1;
}
for loop will be executed in following manner.
foreach loop will be executed in the following manner.
So if you want to write good and efficient program use for loop instead offoreach loop. If you still have some doubt then run the following piece of program and check the output.
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; publicpartialclassTipTest : System.Web.UI.Page { protectedvoid Page_Load(object sender, EventArgs e) { ForLoop(); ForEachLoop(); } publicvoid ForLoop() { System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch(); StopWatch.Start(); for (long i = 0; i < 6000000; i++) { int j = 1; } StopWatch.Stop(); Response.Write(StopWatch.ElapsedMilliseconds + "and"); } publicvoid ForEachLoop() { long[] array = newlong[6000000]; System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch(); StopWatch.Start(); foreach(long x in array) { int j = 1; } StopWatch.Stop(); Response.Write(StopWatch.ElapsedMilliseconds); } }
Note: It must be borne in mind that unless its a real mission-critical situation or an ultra-high performance expectations, priority should be given to code consistency and conventions over performance which in any case wouldn’t be big enough to make a difference
|