[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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; watch.Start(); for (long i = 0; i < num_trials; i++) { if (x % 2 == 0) x = x + 1; else x = x + 3; } watch.Stop(); lblIfTime.Text = watch.Elapsed.TotalSeconds.ToString("0.00") + " seconds"; Refresh(); // Trials using ?:. x = 1; watch.Reset(); watch.Start(); for (long i = 0; i < num_trials; i++) { x = (x % 2 == 0) ? x + 1 : x + 3; } watch.Stop(); 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.