数据点集合清除性能

8

I have this 2 examples:

1 Example:

    Series seria = new Series("name");
    for(int i = 0 ; i < 100000 ; i++)
    {
        seria.Points.Add(new DataPoint(i, i));
    }

    seria.Points.Clear(); // - this line executes 7.10 seconds !!!!!!!!!!

Series 是来自 System.Windows.Forms.DataVisualization dll 的一个类。

2 个示例:

    List<DataPoint> points = new List<DataPoint>();
    for (int i = 0; i < 100000; i++)
    {
        points.Add(new DataPoint(i, i));
    }

    points.Clear();   // - this line executes 0.0001441 seconds !!!!!!!!!!
  • 为什么这些清除方法之间差别如此之大?
  • 我该如何更快地清除seria.Point?
1个回答

9
这是一个非常著名的问题:MSChart DataPointCollection.Clear()的性能问题 建议的解决方法如下:
public void ClearPointsQuick()
{
    Points.SuspendUpdates();
    while (Points.Count > 0)
        Points.RemoveAt(Points.Count - 1);
    Points.ResumeUpdates();
}

在清除点时,数据可视化程序本应暂停更新,但它没有这样做!因此,上述解决方法将比简单调用Points.Clear()快大约一百万倍(当然前提是实际的错误被修复)。


为什么你要使用 while (Points.Count > 0) ... 而不是直接调用 Points.Clear() 呢?因为你已经暂停了更新,所以这不会成为问题。 - Andrey
4
我不清楚Clear()的具体实现细节,无论是它是否存在错误调用ResumeUpdates()或与布局交互的其他函数。因此最好避免使用Points.Clear(),直到修复为止(因此使用了“解决方法”)。 - Teoman Soygul
经过测试,似乎Points.Clear()确实会做一些事情,并且上述方法效果更好。 - fbstj
那个连接到Connect的链接已经失效了,似乎没有直接的替代品。OP的问题已经足够描述问题了。我想,那个链接的另一端可能解释了为什么存在这个问题,但只要这个解决方案有效,谁在乎呢。不过知道原因也是好的。 - DarenW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接