加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 随着时间的推移,添加到列表变得非常慢

发布时间:2020-12-15 19:59:50 所属栏目:百科 来源:网络整理
导读:我正在解析一个大约有1000行的html表.我正在从一个 td中添加~10个字符串.在每一行到列表 string宾语.前200个左右的循环非常快,但随着时间的推移变得越来越慢. 这是我正在使用的代码: Liststring myList = new Liststring(); int maxRows = numRows; for (in
我正在解析一个大约有1000行的html表.我正在从一个< td>中添加~10个字符串.在每一行到列表< 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();
        }

我应该使用数组吗?

编辑:我将上面的代码放在一个新的方法上,该方法在一个新的线程上运行,然后使用以下代码更新我的标签控件:

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个并重复此过程,因此速度较慢但提供了不必事先确定长度的灵活性.这可能是你看到阻力的原因.

谢谢@Dypplvar list = new List< int>(1000);这也是一个优雅的选择,因为@Dyppl认为它是两个世界中最好的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读