views:

227

answers:

2

Which is more efficient?

//Option 1
foreach (var q in baseQuery)
{
  m_TotalCashDeposit += q.deposit.Cash
  m_TotalCheckDeposit += q.deposit.Check
  m_TotalCashWithdrawal += q.withdraw.Cash
  m_TotalCheckWithdrawal += q.withdraw.Check
}

//Option 2
m_TotalCashDeposit = baseQuery.Sum(q => q.deposit.Cash);
m_TotalCheckDeposit = baseQuery.Sum(q => q.deposit.Check);
m_TotalCashWithdrawal = baseQuery.Sum(q => q.withdraw.Cash);
m_TotalCheckWithdrawal = baseQuery.Sum(q => q.withdraw.Check);

I guess what I'm asking is, calling Sum will basically enumerate over the list right? So if I call Sum four times, isn't that enumerating over the list four times? Wouldn't it be more efficient to just do a foreach instead so I only have to enumerate the list once?

+3  A: 

It might, and it might not, it depends.

The only sure way to know is to actually measure it.

Simple code to measure it:

Stopwatch sw = new Stopwatch();
sw.Start();
// your code here
sw.Stop();
Debug.WriteLine("Time taken: " + sw.ElapsedMilliseconds + " ms");
sw.Reset(); // in case you have more code below that reuses sw

You should run the code multiple times to avoid having JITting having too large an effect on your timings.

Lasse V. Karlsen
+1  A: 

I went ahead and profiled this and found that you are correct.

Each Sum() effectively creates its own loop. In my simulation, I had it sum SQL dataset with 20319 records, each with 3 summable fields and found that creating your own loop had a 2X advantage.

I had hoped that LINQ would optimize this away and push the whole burden on the SQL server, but unless I move the sum request into the initial LINQ statement, it executes each request one at a time.

Michael La Voie