tbiro.com

Forums 
   HackPerfCounter
   RADPass
   SHEdit
   Toys
 
   Contact me
   My PGP Key
 

DataGridView SelectRows performance tests


In this article I'll take a closer look at one of the most recommended performance improvements in C#: using foreach vs. a for loop to go through the items in a collection. The victim for this investigation will be the DataGridView control's SelectedRows collection.

I recently completed a project that had abysmal performance exactly because the SelectedRows collection was being looped through with a for loop. The performance was perfectly acceptable for small data samples but when the item count got somewhere over 1000 items we started getting the frozen aplication syndrome. Changing the for loop to a foreach loop improved the performance dramatically.

So this got me thinking about how the foreach would scale compared to the for loop.

I wrote a small application that does only one thing: populate a DataGridView, select all items and then go through each selected item. You can download this at the bottom of this article. The application contains two methods that perform the loop:

  • method 1 using a foreach loop
  • method 2 using a for loop

Inside the loop no real work is done except for incrementing a counter. I did this to minimize the interference other code might have on the performance.

Test results:

Row count foreach for
1000.0156250.015625
2000.0156250.015625
3000.0156250.031250
4000.0156250.031250
5000.0156250.031250
6000.0156250.078125
7000.0312500.062500
8000.0312500.093750
9000.0312500.109375
10000.0312500.140625
20000.0937500.765625
30000.1093751.375000
40000.1562503.078125
50000.1875005.531250
60000.2500008.140625
70000.35937511.437500
80000.48437515.562500
90000.48437520.296875
100000.46875025.390625
Table 1 Comparison of "foreach" and "for" .

Here's what it looks like if we plot a graph with the data.


Figure 1 Comparison of "foreach" and "for" loops for less than 1000 items.


Figure 2 Comparison of "foreach" and "for" loops for less than 10000 items.

Conclusions:

For small sets of data there is no perceptible performance penalty.

Up to 1000 items can be used with reasonable performance but anything larger will have a dramatical effect on performance.

Download code

Comments: tb@tbiro.com






Sitemap generated by Sitemap Manager