Question of Linq Efficiency - foreach vs aggregates

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 suppose I ask: will Sum calling basically list the list correctly? So, if I call the Sum four times, is it not listing on the list four times? Wouldn't it be more efficient to just do foreach, so I only need to list the list once?

+3
source share
2 answers

It may and may not, it depends.

The only reliable way to find out is to actually measure it.

To do this, use BenchmarkDotNet, here is an example that you can run in LINQPad or in a console application:

void Main()
{
    BenchmarkSwitcher.FromAssembly(GetType().Assembly).RunAll();
}

public class Benchmarks
{
    [Benchmark]
    public void Option1()
    {
//        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;
//        }
    }

    [Benchmark]
    public void Option2()
    {
//        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);
    }
}

BenchmarkDotNet - , , , , , JITting GC.


, , , - . , Google , , , , .

:

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

, JITting .

+6

, .

Sum() . SQL 20319 , 3 , 2X.

, LINQ SQL-, LINQ, .

+2

Source: https://habr.com/ru/post/1714997/


All Articles