Is there any performance difference between the following two snippets?
1
IEnumerable<object> enumerable = ...
var observableCollection = new ObservableCollection<object>(enumerable.ToList());
2
IEnumerable<object> enumerable = ...
var observableCollection = new ObservableCollection<object>();
foreach (object o in enumerable)
{
observableCollection.Add(o);
}
Yes there is a performance difference. The second method will raise the
CollectionChangedevent for each item in the list. First will not.This might be ignored if you are not subscribing to the event between creating the collection and adding the items.
If
objOCollectionis assigned to the UI before adding the items, this could cause the UI to perform poorly while the items are being added, as it will have to refresh for each change. Creating the collection in full (whether through the constructor or adding the items) then assigning it to the UI will avoid this.If you are subscribing to the
CollectionChangedevent and looking to react to it for each item, you will not be able to do this with the first method.