First Look at Perfomance of For Loop and ForEachLoop : Part 4

Background

In development there are two types of programmers. Both spend the same amount of time in the office and both are busy writing code. One programmer's code is easily understood and performance is very good and the programmer code is easily understood but the performance is very slow. I like the first programmer because the code runs smoothly and the performance is fast.
 
Road map

You can see other performance issues in my other articles.
 
 
Performance

Performance is a main issue in any program or web application. If performance is slow in an application then we avoid the application. In development life many steps increase the application performance. I will not write every step there. I focus only on looping performance in the current article.    
 
In this article we have two loops, both do the same thing and the output is also the same. If you hear the word loop then think about a for Loop because this loop is the traditional loop. Your mind thinks of something when you hear the word loops. I think the picture looks as in: 
 
  1. For(,,) //Loops without condition.     
  2. {    
  3. }   
 Note

The preceding loop is working fine and is an infinite loop because it has no loop terminate condition.
Loops

The C# language has two types of loops, one is a for loop and the other is a foreach loop. 
I think that's enough of the loops information. I have already said in this article we will focus on which provides the best performance. Let's move on.
 
I have a special tool for performance checking both loops. I created a window application with a flowchart.
 
 
 I have two functions. 
  1. ForLoop();    //For Loops
  2. ForeachLoop(); // ForEach Loop            
 Make a another function for adding a value in the Data Table. We can check both loop arrays, list and so on but I want to check on the Data Table. So we can make another function for Data table.
  1. add_value();  
  2.        
And a function for the Page_Load event.
  1. private void Form1_Load(object sender, EventArgs e)  // Page Load Event call here.
  2.        {  
  3.            MessageBox.Show("Wait for some moments");  
  4.            add_value();  //Add value in Data Table
  5.            ForLoop();  // For Loop
  6.                 
  7.                ForEachLoop();  // Foreach Loop
  8.                
  9.            chart1.Series["For"].ChartType =    SeriesChartType.Bar;  
  10.            chart1.Series["For"].Color = Color.Red;  
  11.            chart1.Series["ForEachLoop"].ChartType =  
  12.                       SeriesChartType.Bar;  
  13.            chart1.Series["ForEachLoop"].Color = Color.Blue;    
  14.        } 
 
 Add data into the Data Table. 
  1. DataTable dt = new DataTable();  
  2.       int j = 0;  
  3.       int i = 0;  
  4.       public void add_value()  
  5.       { 
  6.           DataRow row;  
  7.           DataColumn col = new DataColumn("id");  
  8.           dt.Columns.Add(col);  
  9.           for (i = 0; i < 10000000; i++)  //
  10.           {   
  11.               row = dt.NewRow();  
  12.               row["id"] = i;  
  13.               dt.Rows.Add(row);  
  14.   
  15.           }  
  16.       } 
 
For loop performance

Check out this function. It sets the loop start time. 
  1. string startingTime = DateTime.Now.ToLongTimeString();    
The loop will execute i exceeds the dt.rows.count(). 
  1. public void ForLoop()  
  2.        {  
  3.           
  4.            for (int i = 0; i < dt.Rows.Count; i++)  
  5.            {
  6.  
  7.            }  
  8.  
  9.        } 
 Get the value from the Data Table using a for loop one by one. 
  1. for (int i = 0; i < dt.Rows.Count; i++)  
  2.            {  
  3.                string s = dt.Rows[i]["id"].ToString(); //Get the value one by one like dt.Rows["Row Index no"]["column Name"].Tostring(); 
  4.   
  5.            } 
Set the end time after the completion of the loop execution.
  1. endtime = DateTime.Now.ToLongTimeString();               
 Get the difference between the looping start and looping end times. 
  1. TimeSpan t1 = DateTime.Parse(endtime).Subtract(DateTime.Parse(startingTime));              
Assign the value of our loop execution times.
  1. chart1.Series["For"].Points.AddXY(j, t1.TotalSeconds);  //our chart line move 0 to value of take the loop for complete looping.
  2.         label1.Text = t1.ToString(); 
foreach Loop Performance

With the same process as the for loop, make a function to get the foreach loop performance. 
  1. public void ForEachLoop()  
  2.         {  
  3. //empty function .......  
  4.   
  5.         } 
Set the loop start time. 
  1. string startingTime = DateTime.Now.ToLongTimeString();            
Create the foreach loop.
  1. foreach (DataRow item in dt.Rows) //dt.rows is collection all row in the dt Data Table.
  2.            {  
  3.                string s = item["id"].ToString(); //Item is DataRow so i get the value these type item["column name"].
  4.            } 
Set the loop end time.
  1. endtime = DateTime.Now.ToLongTimeString();        
Get the difference between and count how much time the foreach takes to complete all the processes.
  1. TimeSpan t1 = DateTime.Parse(endtime).Subtract(DateTime.Parse(startingTime));  
  2.          chart1.Series["ForEachLoop"].Points.AddXY  
  3.                                (j, t1.TotalSeconds);                 
  4.          label2.Text = t1.ToString(); 
The output. My foreach has better performance than the for loop.
  
 
 Final word

I am confident about the foreach loop performance. 
 

Up Next
    Ebook Download
    View all
    Learn
    View all