当前位置 : 主页 > 手机开发 > 其它 >

Linq效率问题 – foreach与聚合

来源:互联网 收集:自由互联 发布时间:2021-06-22
哪个更有效率? //Option 1foreach (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 2m_TotalC
哪个更有效率?

//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);

我想我要问的是,调用Sum将基本列举在列表上吗?所以,如果我四次打电话给Sum,是不是列举了四次列表呢?只做一个foreach不是更有效率所以我只需要列举一次列表吗?

它可能,也可能不是,它取决于.

唯一确定的方法是实际测量它.

测量它的简单代码:

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对您的计时产生太大的影响.

网友评论