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 |
|
100 | 0.015625 | 0.015625 |
200 | 0.015625 | 0.015625 |
300 | 0.015625 | 0.031250 |
400 | 0.015625 | 0.031250 |
500 | 0.015625 | 0.031250 |
600 | 0.015625 | 0.078125 |
700 | 0.031250 | 0.062500 |
800 | 0.031250 | 0.093750 |
900 | 0.031250 | 0.109375 |
1000 | 0.031250 | 0.140625 |
2000 | 0.093750 | 0.765625 |
3000 | 0.109375 | 1.375000 |
4000 | 0.156250 | 3.078125 |
5000 | 0.187500 | 5.531250 |
6000 | 0.250000 | 8.140625 |
7000 | 0.359375 | 11.437500 |
8000 | 0.484375 | 15.562500 |
9000 | 0.484375 | 20.296875 |
10000 | 0.468750 | 25.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
|