Ksice
Ksice

Reputation: 3327

List or ObservableCollection?

Is there any difference in performance to use ObservableCollection, which (as I understand) refreshes view each time item added to collection, or instead use simple List collection, and refresh whole view when all elements already added?

And is the scenario with List as decried above even possible? How to implement this then?

I'm asking because my ItemsControl is slow, and I wonder if it would be better to use simple List instead ObservableCollection. I need to refresh the view only once at a time, when actually all elements already added to collection.

Upvotes: 3

Views: 7921

Answers (2)

Ian
Ian

Reputation: 323

ObservableCollection<T> implements IList<T> just as List<T> does. The main difference is of course, that it implements INotifyCollectionChanged which allows WPF to bind to it.

The ObservableCollection<T> throws an event after each change so the UI can Refresh. If you are adding a lot of Items sequentially, it can have some impact to your performance but that is unlikely. You can test this rather simple by using the Constructor which takes a List:

var originalList = new List<SomeClass>();

foreach ([..])
{
  originalList.Add(someInstance);
}

ObservableCollection<SomeClass> uiCollection = new ObservableCollection<SomeClass>(originalList);

This way you can create you complex List of objects and after its finished you can create an ObservableCollection out of it which you will Bind to on the UI.

Upvotes: 5

mm8
mm8

Reputation: 169420

If you don't plan to add or remove items dynamically at runtime, you might as well use a List<T> instead of an ObservableCollection<T>. The difference in performance will be negligible though.

The special thing about the ObservableCollection<T> is that it implements the INotifyCollectionChanged interface: https://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged(v=vs.110).aspx

WPF subscribes to the CollectionChanged event of any collection that implements this interface to listen for collection changes. So if you for some reason want to create your own custom collection that supports change notifications, you could create a class that implements this interface.

I strongly doubt that your performance issues is related to the type of source collection you are using though. You should make sure that UI virtualization is enabled and go trough the following list of suggestions on how to improve the performance of Controls in WPF: https://msdn.microsoft.com/en-us/library/cc716879(v=vs.110).aspx

Upvotes: 4

Related Questions