简体   繁体   中英

How can I speed up DataColumn check?

string specifiedSymbol = "MySymbol";

Systems.Data.DataTable table = CreateInitialTable();

if (!table.Columns.Contains(specifiedSymbol))
       table.Columns.Add(specifiedSymbol, Type.GetType("System.Double"));

I have just profiled the above statment and it seems that the IF takes around 10ms. This is a long time for my app. How else could I check if a column exists in datatable more efficiently?

It's not obvious what classes or imports you are using, so I will provide a generic answer.

When calling Contains() on a collection which has O(n) complexity (or worse), performance can be improved by doing one of the following:

  • Manage a separate HashSet in which you mirror any changes made to the O(n) collection, then use the Contains() -method of the HashSet to test for presence.
  • If you cannot track the changes to your collection, you may still be able to improve performance by creating a HashSet and filling it with the contents of the collection every time you need to call Contains() iff you need to call it multiple times in a row, ie without intermittent change-operations and the time lost using the collection's implementation taking longer than creating a new HashSet from its contents entirely. This is less desirable than the former for performance reasons, but more desirable for code-manageability.

The best case scenario is being able to write a new class which inherits from the collection's class and putting all the logic in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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