简体   繁体   English

更新数据表的最快方法

[英]Fastest way to update datatable

Assume we have a DataTable with 100 columns and 100 rows. 假设我们有一个包含100列和100行的DataTable。 We have a dictionary of values like this that contains 100 members: 我们有一个这样的值字典,其中包含100个成员:

Dictionary<int, string> dictionary = GetValues();

In above dictionary key is index of the Datatable and value of dictionary is target value that we want to update in Datatable. 在上面的字典中,键是数据表的索引,字典的值是我们要在数据表中更新的目标值。

What's the fastest way to update the Datatable? 更新数据表的最快方法是什么? I use this way but it's slow : 我用这种方式,但是很慢:

      foreach (var pair    in dictionary)
        {

            timeTable.Rows[pair.Key].SetField(columnIndex, pair.Value);
        }

Assuming we have to update all rows of 40 columns, it doesn't have good performance. 假设我们必须更新40列的所有行,那么它的性能就不好。 I was thinking that Datatable is like a Matrix and it shouldn't take time at all when you want to update a cell on Matrix while you have indexes of the row and the column. 我以为Datatable就像是一个Matrix,当您有行和列的索引时,如果要更新Matrix上的单元格,它根本不需要花费时间。

DataTable is a very expensive structure that dos a lot behind the scenes (particularly because they are designed to handle anything). DataTable是一种非常昂贵的结构,它在后台做很多事情(特别是因为它们旨在处理任何事情)。

If performance is critical consider: 如果性能至关重要,请考虑:

  • Creating your own structure, such as a class encapsulating an array of strings arrays (eg a strings matrix, on which access will be very fast) 创建自己的结构,例如封装字符串数组数组的类(例如,字符串矩阵,对其进行访问将非常快)

  • Udating your table in parallel (since you are never accessing the same row), knowing that DataTable is NOT thread safe for writing operations. 并行处理表(因为您从不访问同一行),因为知道DataTable对于写操作不是线程安全的。

eg 例如

// Probably not thread safe, after the MSDN documentation
Parallel.ForEach(Dictionary, pair =>
    {
      timeTable.Rows[pair.Key].SetField(columnIndex, pair.Value);
    });

EDIT: This will not work in the general case (write operations even on distinct rows might affect global state of the DataTable, so I suggest that you go with your own structure if performance is critical, and if you don't need specific features of the DataTable) 编辑:这在一般情况下将不起作用(即使在不同的行上进行写操作也可能会影响DataTable的全局状态,因此,如果性能至关重要,并且如果您不需要特定的功能,则建议您使用自己的结构数据表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM