简体   繁体   中英

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 (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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM