Reputation: 1177
Which is faster ObservableCollection or IEnumerable to load a listbox?
I am currently using an IEnumerable as the ItemSource of the Listbox.
Will it have any impact on the performance if I change this to ObservableCollection, if it is even possible?
Upvotes: 2
Views: 9029
Reputation: 11926
If you bind to a collection that implements IEnumerable
and that is not an ObservableCollection
, for example a List
, the binding target will not be notified of items added/removed.
Not using a ObservableCollection does only make sense if the number of items in the collection does not change. Only then it makes sense to compare ObservableCollection with other objects. If the number of items change, then you do not have any choice but using an ObservableCollection.
In addition, as already pointed out by other users, you do not have to compare ObservableCollection with IEnumerable, but with a class implementing IEnumerable.
As an example, a comparison ObservableCollection - List can be found in Stack Overflow question ObservableCollection<> vs. List<>.
Upvotes: 1
Reputation: 9588
I'm quite new to WPF and C#, but what I have understood so far is that if you use an IEnumerable as ItemSource, such as a List, you won't be able to see changes in that List unless you replace it with a different one:
IEnumerable<int> myList = new List<int>();
myList.Add(3);
In this case (provided that you do all the necessary stuff to inform your GUI that myList
is changed) nothing will happen. If you do something like this, instead:
myList = new List<int> { 100, 200, 300 };
your GUI will be informed.
If you use a ObservableCollection, instead, your GUI will be informed even when you add a new element with the Add
method. So you have to decide whether you want to add elements to your ListBox or not.
Upvotes: 1
Reputation: 417
That really depends on which class is implementing the IEnumerable. IEnumerable is simply an interface and any number of classes could be behind the actual implementation. You don't really bind the IEnumerable, since that is an interface, but you are binding some collection/list that implements IEnumerable. ObservableCollection also implements IEnumerable so should be able to safely use that as the ItemSource instead.
Enumerating through a IEnumerable to fill a ListBox should never be a performance bottleneck in your application, unless you would be using some custom class that does a lot of logic when iterating through values, in which case your design would probably be flawed.
That being said, the best way is of course to simply measure. There is no substitute for measuring and making assumptions is always likely to come back to bite you later.
Upvotes: 4