哪个更有效率? //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对您的计时产生太大的影响.
