Best performance for ObservableCollection.AddRange

23,816

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

Share:
23,816
Charles W
Author by

Charles W

Updated on October 29, 2020

Comments

  • Charles W
    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
      Jeroen Vannevel about 10 years
      If you want to know the performance, measure it.
    • BartoszKP
      BartoszKP almost 9 years
      Concat does not modify oc so the second approach doesn't make sense.
    • Raven
      Raven over 8 years
      To clarify what @BartoszKP wrote Concat is a linq method and does not modify the collection. It returns a new IEnumerable<T> that contains both oc and collection.
    • Charles W
      Charles W over 8 years
      Thanks - I've edited my question removing the concat example.
  • Michael Cook
    Michael Cook about 10 years
    This looks like another great solution: stackoverflow.com/questions/670577/…