Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sorting using CollectionViewSource.SortDescriptions is slow?

This is the default sort method when you click on a column header in a DataGrid. When the underlying list contains 100,000 items, it takes about 20 seconds to refresh the view. Same delay can be observed when setting SortDescriptions on a CollectionView.

Sorting by using ListCollectionView.CustomSort or by sorting and re-assinging the list works almost instantly.

Why is this delay? Is this just a "reflection tax" on the bound properties?

like image 394
Sergey Aldoukhov Avatar asked Oct 27 '09 21:10

Sergey Aldoukhov


1 Answers

You are right, this is a reflection tax. I looked very closely on DataGrid performance some time ago, and reflection was a bottle neck here. No matter how fast is sorting algorithm, they don't cache property's value between two comparisons. So, even if you have n*ln(n) comparisons, with n == 100 000 you'll get ~1 000 000 operations. Each operand uses reflection to get value, so you have 2 000 000 calls to reflection in tax :) ... ListCollectionView.CustomSort is ideal solution here.

PS: At the end of the day, we wrote ListView-based grid, because we were not satisfied with DataGrid rendering performance too... But that's another story :)

like image 92
Anvaka Avatar answered Oct 02 '22 09:10

Anvaka