In many cases for and foreach have the same function, choose for or foreach Many people may be looking at their preferences, this test tries to compare their execution efficiency by really testing data. I hope we can give you some help when it comes to them.
Test environment:
Hardware environment: PIII800 + CPU456
Software Environment: VisualStudio.NET + C #
Test Cases:
Use result sets to store records, initialize add records to result sets
Sampling analysis for record number of 10000,100000,1000000 records respectively
The key test comparison code is as follows, and the functionality is exactly the same:
foreach Start time
Datetime3 = System.DateTime.Now.TimeOfDay.ToString ();
foreach (DataRow row in relationdata.tables[relationdata.relationinfo_table]. Rows)
Buffer = Row[relationdata.pk_table_name]. ToString ();
Datetime4 = System.DateTime.Now.TimeOfDay.ToString ();
For start time
Datetime5 = System.DateTime.Now.TimeOfDay.ToString ();
for (int j=0;j<1000000;j++)
Buffer = relationdata.tables[relationdata.relationinfo_table]. Rows[j][relationdata.pk_table_name]. ToString ();
Datetime6 = System.DateTime.Now.TimeOfDay.ToString ();
Test results:
10,000 Records:
foreach Read time: 16:29:34.2577584
foreach End time: 16:29:34.2677728
For read start time: 16:29:34.2677728
For read end time: 16:29:34.2878016
100,000 records:
foreach Read time: 16:31:10.1055808
foreach End time: 16:31:10.1957104
For read start time: 16:31:10.1957104
For read end time: 16:31:10.4460704
1 million records:
foreach Read time: 16:33:12.6217504
foreach End time: 16:33:13.6332048
For read start time: 16:33:13.6332048
For read end time: 16:33:18.7906208
Result Analysis:
1 for 10,000 records you can see that
foreach uses 0.0100144
for loop 0.0300432
foreach takes exactly the time for the For loop 1/3
2) for 100,000 records
foreach used the 0.0901296
The For loop uses the 0.2503600
foreach for the time spent in the for loop 36%
3) For the results of 1 million records, you can see that
foreach used 1.0114544
for loop with 4.1574160
The time that foreach takes is the 25%
for the loop.
By analyzing these test results, you can see that the foreach with the original for statement has
For better execution efficiency, foreach's average time spent is only for30%. With the test results, we recommend using a more efficient foreach when both for and foreach are available. While testing
Our additional discovery is that the time used for writing data is about 10 times times the time it takes to read data.:P