views:

668

answers:

1

I would like to know why according to this article and observable collection binds significantly faster(20 ms vs 1685ms, that's 800X faster) than a List<> collection in WPF. I looked at the internals of ObservableCollection and it uses a List as it's storage collection object(I used reflector and saw this in the constructor)

public Collection()
{
    this.items = new List<T>();
}

So what's going on here?

+7  A: 

The comparison in that article isn't between two simple binding operations, those measurements refer to a scenario in which you add a single item to a WPF ListBox that is already bound to either a List<T> or an ObservableCollection<T>.

As the author remarks:

...the CLR List<T> object does not automatically raise a collection changed event. In order to get the ListBox to pick up the changes, you would have to recreate your list of employees and re-attach it to the ItemsSource property of the ListBox. While this solution works, it introduces a huge performance impact. Each time you reassign the ItemsSource of ListBox to a new object, the ListBox first throws away its previous items and regenerates its entire list.

This explains the performance difference. Even though ObservableCollection<T> is backed by a List<T>, it implements the INotifyCollectionChanged interface, which renders all that extra processing unnecessary.

Jeff Sternal
More precisely INotifyCollectionChanged is implemented by ObservableCollection<T>
Bryce Kahle
Thank you, Bryce - corrected.
Jeff Sternal
So, if we have a List<T> of 1000 items and an ObservableCollection<T> of 1000 items they would take the same amount of time, right? It makes sense.
Jose
If I understand correctly, that is correct - everything else being equal (<T> being the same type, nothing crazy happening when accessing the bound property, etc.), they would take the same amount of time.
Jeff Sternal