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.
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.
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.