[英]Is there a more efficient alternative to nesting an if statement within a for loop in C# when dealing with large numbers of iterations?
I have a method which consists of an if statement nested within a for loop: 我有一个方法,该方法由嵌套在for循环中的if语句组成:
for (int i = 0; i < val; i=i+2)
{
for (int j = i+1; j < val; j=j+1)
{
actualDistance = actualDistance + (ulong)Math.Max(revenue[i], revenue[j]) * (ulong)Math.Abs(point[j] - point[i]);
if (j + 1 < val)
{
actualDistance = actualDistance + (ulong)Math.Max(revenue[i+1], revenue[j+1]) * (ulong)Math.Abs(point[j+1] - point[i+1]);
}
}
}
However, if val represents a number within the tens of millions, then the method takes a very long time during runtime since it is used in both the for and if loops. 但是,如果val表示数千万以内的数字,则该方法在运行时会花费很长时间,因为它在for和if循环中都使用。
Is there a better and more efficient way of doing this? 有没有更好,更有效的方法? The code as it currently stands is too time inefficient. 目前的代码时间效率太低。
Either I'm missing something or your code is equivalent to: 我遗漏了一些东西,或者您的代码等效于:
for (int j = i+1; j < val; j=j+1)
{
actualDistance = actualDistance + (ulong)Math.Max(revenue[i], revenue[j]) * (ulong)Math.Abs(point[j] - point[i]);
actualDistance = actualDistance + (ulong)Math.Max(revenue[i+1], revenue[j+1]) * (ulong)Math.Abs(point[j+1] - point[i+1]);
}
actualDistance = actualDistance - (ulong)Math.Max(revenue[i+1], revenue[val]) * (ulong)Math.Abs(point[val] - point[i+1])
Your if
statement will be almost always true and the only case when it's false is when j == val - 1
, so you can just always run the code inside if
statement and than subtract that last case outside of for
loop. 您的if
语句几乎总是true,唯一的情况是false,当j == val - 1
,因此您可以始终在if
语句中运行代码,然后在for
循环之外减去最后一种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.