Best performance for ObservableCollection.AddRange
Given that Concat<T>
is an extension method it is almost certainly just calling .Add()
under the covers, it can't have internal knowledge of the class. You could use ildasm.exe to see what's going on for sure.
I hit performance issues for this very case using ObervableCollection<T>
a few years ago. The solution I eventually arrived at was to implement IList<T>
and INotifyCollectionChanged
with a custom implementation that supports raising a single CollectionChanged event with an actual collection delta (instead of per-item events) in response to a call to AddRange<T>
. Check out the documentation for NotifyCollectionChangedEventArgs to get the details.
Charles W
Updated on October 29, 2020Comments
-
Charles W over 3 years
I'm writing an extension method for ObservableCollection and have read that the .Add function raises 3 property changed events per call,
So that something like this is a bad idea:
public static void AddRange<T>(this ObservableCollection<T> oc, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } foreach (var i in collection) { oc.Add(i); } }
Are there any other solutions to this?
-
Jeroen Vannevel about 10 yearsIf you want to know the performance, measure it.
-
BartoszKP almost 9 years
Concat
does not modifyoc
so the second approach doesn't make sense. -
Raven over 8 yearsTo clarify what @BartoszKP wrote
Concat
is a linq method and does not modify the collection. It returns a newIEnumerable<T>
that contains bothoc
andcollection
. -
Charles W over 8 yearsThanks - I've edited my question removing the concat example.
-
-
Michael Cook about 10 yearsThis looks like another great solution: stackoverflow.com/questions/670577/…