lundi 16 novembre 2020

Performance of If/Else If versus OR-operator in C#

I got curious about the performance implications of formating OR-based logic differently, so I ran a simple and probably somewhat unscientific test. I ran the code below 10 times with the if-statement set to true (to trigger Case 1) and 10 times with it set to false (to trigger Case 2). I used this site to test the code and relied on its reported "absolute running time".

The result I got was that Case 1 takes an average of 0.354 seconds to run, while Case 2 takes an average of 0.442 seconds to run. The numbers were fairly consistent individually - in Case 1 they varied within a range of 0.04 and in Case 2 they varied within a range of 0.09, and there was no overlap at all, so it seems at first blush to be a clear difference.

Both cases yield the same result for counter - 38571428 in this case, but the same value for other toCount values I tried as well. My understanding is that else-if statements are not evaluated if a previous if or else-if statement evaluated to true, so from a logic standpoint I think the two cases are doing the same thing.

I don't have a good intuitive sense of why Case 1 performs better than Case 2. Could someone shine some light on this? I'm interested in a general sense, for the sake of better understanding how different ways of structuring C# logic might impact performance, so I'm hoping there might also be underlying principles to be understood by this example, but even just the explanation for this case seems interesting.

int counter = 0;
int toCount = 50000000;
//Case 1
if (false)
{
    for (int iNum = 0; iNum < toCount; ++iNum)
    {
        if (iNum % 2 == 0 || iNum % 3 == 0 || iNum % 5 == 0 || iNum % 7 == 0)
        {
            ++counter;
        }
    }
}
//Case 2
else
{
    for (int iNum = 0; iNum < toCount; ++iNum)
    {
        if (iNum % 2 == 0)
        {
            ++counter;
        }
        else if (iNum % 3 == 0)
        {
            ++counter;
        }
        else if (iNum % 5 == 0)
        {
            ++counter;
        }
        else if (iNum % 7 == 0)
        {
            ++counter;
        }
    }
}
Console.WriteLine("Result: " + counter.ToString());

Aucun commentaire:

Enregistrer un commentaire