Ternary operator is twice as slow as an if-else block?

I read everywhere that ternary operator is supposed to be faster than, or at least the same as, its equivalent ifelse block.

However, I did the following test and found out it’s not the case:

Random r = new Random();
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
    array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);

long value = 0;
DateTime begin = DateTime.UtcNow;

foreach (int i in array)
{
    if (i > 0)
    {
        value += 2;
    }
    else
    {
        value += 3;
    }
    // if-else block above takes on average 85 ms

    // OR I can use a ternary operator:
    // value += i > 0 ? 2 : 3; // takes 157 ms
}
DateTime end = DateTime.UtcNow;
MessageBox.Show("Measured time: " + (end-begin).TotalMilliseconds + " ms.\r\nResult = " + value.ToString());

My computer took 85 ms to run the code above. But if I comment out the ifelse chunk, and uncomment the ternary operator line, it will take about 157 ms.

Why is this happening?

10 Answers
10

Leave a Comment