c# - 添加到 List<t> 随着时间的推移变得非常慢

标签 c# winforms

我正在解析一个大约有 1000 行的 html 表格。我从一个 <td> 添加 ~10 个字符的字符串在每一行到一个list<string>目的。前 200 次左右的循环非常快,但随着时间的推移变得越来越慢。

这是我正在使用的代码:

List<string> myList = new List<string>();
        int maxRows = numRows;


        for (int i = 1; i < maxRows; i++)
        { 
            TableRow newTable = myTable.TableRows[i];
            string coll = string.Format("{0},{1},{2},{3},{4}",newTable.TableCells[0].Text,newTable.TableCells[1].Text,newTable.TableCells[2].Text,newTable.TableCells[3].Text,newTable.TableCells[4].Text);
            myList.Add(coll);
            label1.Text = i.ToString();
        }

我应该改用数组吗?

编辑: 我将上面的代码放在一个新方法中,该方法在新的 Thread 上运行。然后用这段代码更新我的标签控件:

label1.Invoke((MethodInvoker)delegate
                {
                    label1.Text = i.ToString();
                });

程序以一致的速度运行并且不会阻塞 UI。

最佳答案

如果您大致知道集合中的范围(项目数),最好使用数组。

Reason : Every time you add an element to the List if the list is full it allocates new block of memory to hold the double the current space and copies everything there and then keeps appending the additional entries till it becomes full, and one more allocation copy cycle.

以下是它的工作原理 AFAIK,默认从 16 个元素开始, 当您将第 17 个元素添加到列表中时,它会分配 32 个元素并在那里复制 16 个,然后继续进行 17 到 32。并重复此过程,因此速度较慢但提供了不必事先确定长度的灵 active 。这可能是您看到阻力的原因。

感谢@Dyppl var list = new List<int>(1000);这也是一个优雅的选择,正如@Dyppl 所建议的那样,它是两全其美的选择。

关于c# - 添加到 List<t> 随着时间的推移变得非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5176916/

相关文章:

c# - 在程序集中嵌入 Global.asax

c# - EntityCollection<TEntity> 的 foreach 错误

c# - 我们是否使类的对象具有私有(private)构造函数?

javascript - 如何在 ASP.NET C# 中针对 RangeValidator 错误调用 javascript 代码?

winforms - 如何让 DataGridView 在绑定(bind)到 IList 对象时忽略某些属性

c# - 以编程方式单击复选框

c# - 如何使用按钮向 DataGridView 添加新行

c# - 如何为 OpenFileDialog 框中的取消按钮编写代码

c# - 缩放 2D 图形 Pane 上的信号

c# - TPL 完成与完成