ObservableCollection.AddRange的最佳性能 [英] Best performance for ObservableCollection.AddRange
问题描述
我正在为ObservableCollection写一个扩展方法,并且已经阅读到.Add函数每次调用都会引发3个属性更改事件,
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); }
}
还有其他解决方案吗?
推荐答案
鉴于Concat<T>
是扩展方法,几乎可以肯定只是调用.Add()
在幕后,它不具备该类的内部知识.您可以使用ildasm.exe来确定正在发生的事情.
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.
几年前,我在这种情况下使用ObervableCollection<T>
遇到了性能问题.我最终到达的解决方案是使用自定义实现来实现IList<T>
和INotifyCollectionChanged
,该实现支持响应于对AddRange<T>
的调用而引发带有实际集合增量(而不是每个项目的事件)的单个CollectionChanged事件.请查看NotifyCollectionChangedEventArgs的文档以获取详细信息.
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.
这篇关于ObservableCollection.AddRange的最佳性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!