raBinn
raBinn

Reputation: 182

Performance: Iterate linq VS iterate datatable

A general culture question:

In a relatively small set of records (5000 records for example) it would be more optimal to iterate over Linq objects or over a Datatable.

Example with linq:

var _rows_ref_carga = from _row in list_cargas
                 where ref_carga == "XXXXX"
                 select _row;
                 

foreach (var _r in _rows_ref_carga)   {
   OTHER OPERATION
}

Example with DataTable:

 foreach (DataRow _r in _datatable.Rows)   {
       OTHER OPERATION
    }

My question is: iterate over "_rows_ref_carga" is more efficient that iterate over "_datatable.Rows" ???

Thanks.

Upvotes: 0

Views: 173

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

With the edit, it looks like you're comparing LINQ-to-Objects over a DataTable, vs foreach over a DataTable (with a Where vs an if). This would be a great thing to investigate with a benchmarking tool such as benchmarkdotnet with your realistic data. Other things to consider:

  • how many matches do you expect? If it is 1, would a dictionary be a better idea? Or a ToLookup? (Assuming the data doesn't change constantly)
  • would a List-T have fewer overheads?

However! Yes, LINQ-To-Objects adds a layer of abstraction and indirection, which means: overheads. Normally this overhead isn't important, and the clarity of code is worth it. If the code in question is performance critical, then the foreach with if would usually be measurably quicker, but only by a little. The more relevant factors are usually:

  1. Can you improve the underlying store? (Hence my mention of list, dictionary, lookup), and
  2. Can you improve the OTHER OPERATION, which is usually the main time taken; if the iteration is only 0.1% of the cost anyway, improving it isn't a good use of your time

Upvotes: 2

Related Questions