Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best performance for ObservableCollection.AddRange

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?

like image 769
Charles W Avatar asked Mar 03 '14 18:03

Charles W


1 Answers

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.

http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedeventargs(v=vs.110).aspx

like image 136
Michael Cook Avatar answered Sep 22 '22 01:09

Michael Cook