Compare the speeds of the conditional operator (ternary operator ?:) and the if-else statement in C#

The conditional operator (also called the ternary operator) looks confusing enough that some programmers assume it must be more efficient than a comparable but longer if-else statement. This example uses the following code to compare the speeds of the conditional operator and an if-else statement.

Stopwatch watch = new Stopwatch();
long x;

// Trials using if.
x = 1;
for (long i = 0; i < num_trials; i++)
    if (x % 2 == 0) x = x + 1;
    else x = x + 3;
lblIfTime.Text =
    watch.Elapsed.TotalSeconds.ToString("0.00") +
    " seconds";

// Trials using ?:.
x = 1;
for (long i = 0; i < num_trials; i++)
    x = (x % 2 == 0) ? x + 1 : x + 3;
lblConditionalTime.Text =
    watch.Elapsed.TotalSeconds.ToString("0.00") +
    " seconds";

The code starts a Stopwatch and then enters a loop that uses an if-else statement. The loop determines whether the variable x is odd or even and adds either 1 or 3 to it. When the loop finishes, the program displays the elapsed time.

The program then repeats the same steps using the conditional operator instead of an if-else statement.

You can see from the figure that the difference between the two approaches is negligible. In this trial, after 100 million tests the difference in time was only 30 milliseconds. Variations in the operating system are more significant, so if you run the tests several times you will get different results and sometimes the conditional operator will be faster.

The moral is you should use whichever of these statements seems easier to read and understand and not worry about performance. For a very short statement, you may find ?: more compact than if-else. Often ?: is confusing so I usually pick if-else instead.

(Note that it’s a good thing that the performance of the two statements is the same. It means the C# code is being converted into comparable IL code before execution. It would be bad if Visual Studio compiled one of these two equivalent statements into something that was less efficient than the other. But it’s also useful to check.)

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in performance, syntax and tagged , , , , , , , , , , . Bookmark the permalink.

5 Responses to Compare the speeds of the conditional operator (ternary operator ?:) and the if-else statement in C#

  1. Sam says:

    There are a few things wrong with this “test”.

    a) You can’t use DateTime.Now to reliably benchmark performance. The Stopwatch class was designed for benchmarking; use it instead.

    b) The ?: operator will create equivalent IL to if-else, so how could one possibly be faster than the other?

    I suggest you read Eric Lippert’s blog as he discussed these types of issues before.

  2. Rod Stephens says:

    a) You can if you perform a lot of trials. StopWatch is wonderful but you can do even better if you really care. But when you’re talking about a difference of a few milliseconds (or even microseconds in some cases) out of 2.5 seconds, the difference isn’t really significant. If you want to try to time a single test, then yes you need a better timer. But in that case the task switching of the operating system can totally blow your measurement away.

    b) True. If you feel like reading the IL, look at If you really dig into it, you can see how the performance of any set of related statements should compare.

  3. Johnny Boy says:

    You have a a nice article but it would be great if you compare the switch/case statement too. Here’s a blog similar to yours, but does just that:

    Otherwise, keep up the great posts!

  4. Rod Stephens says:

    You’re right. But the real intent here was to determine whether you should use the more confusing ?: syntax or stick with the longer but easier to read if-then-else syntax.

    Still the article you mention is worth reading.

    I’ll post a follow-up in a few days that compares if-then-else with switch a bit more and shows (an effect that the other article missed).

  5. Pingback: Compare the performance of if-else and switch statementsC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.