44

Possible Duplicate:
Is the conditional operator slow?

I'm a massive user of the ? operator in C#. However my project manager frequently warns me that using ? operator might cost some performance compared to the If-Else statements in a large scale application. So I'm told to avoid using it. However, I love using it because it is concise and sort of keeps the code clean.

Is there such performance overhead when using ? operator?

Community
  • 1
  • 1
Paras
  • 2,997
  • 6
  • 35
  • 46
  • 1
    You can get good answers here...in this http://stackoverflow.com/questions/3312786/benefits-of-using-the-conditional-ternary-operator – Mayank Pathak Jul 25 '12 at 05:15
  • Please, consider reading this thread too: http://stackoverflow.com/questions/2259741/is-the-conditional-operator-slow. IMHO, your manager is equivocated – Andre Calil Jul 25 '12 at 05:16
  • I don't think the other linked questions address the supposed performance overhead (which I cannot see where it would be coming from). – Thilo Jul 25 '12 at 05:20
  • 3
    May this link help you. http://embeddedgurus.com/stack-overflow/2009/02/efficient-c-tips-6-dont-use-the-ternary-operator/ – SMK Jul 25 '12 at 05:22
  • Note that the link to the Stack Overflow blog (no, the *other* one) talks about C and all the comments are about how their particular compiler creates the exact same assembly, but that there may be older/other compilers that prefer if/else. This does not seem to apply to C# where there is only one compiler that almost everyone uses. – Thilo Jul 25 '12 at 05:27
  • Here is a question about the opposite (ternary being faster): http://stackoverflow.com/questions/4192225/ternary-operator-vs-if-statement-question-of-prettiness?rq=1 Not about C#, though. – Thilo Jul 25 '12 at 05:28
  • 1
    Taking care about difference in performance of these two concepts in C#, where between the code and machine lie several layers, seems silly to me. – René Kolařík Jul 25 '12 at 05:37
  • 4
    Neither the if/else, ternary, nor logical short circuits were designed specifically with the intent of outperforming the others. They were designed to facilitate code clarity. Use them for that. If there's a situation where performance is at issue (after profiling), then start looking at better algorithms before worrying about the microscopic differences between how the compiler interprets various branching mechanisms. – DavidO Jul 25 '12 at 05:41
  • yea. Its that very reason he is in Management ;) – user20358 Jan 26 '17 at 15:53

5 Answers5

126

I ran 100 million Ternary Operators and 100 million If-Else statements and recorded the performance of each. Here is the code:

Stopwatch s = new Stopwatch();
// System.Diagnostics Stopwatch
int test = 0;
s.Start();
for(int a = 0; a < 100000000; a++)
    test = a % 50 == 0 ? 1 : 2;
s.Stop();

s.Restart();
for(int b = 0; b < 100000000; b++)
{
    if(b % 50 == 0)
        test = 1;
    else
        test = 2; 
}
s.Stop();

Here is the results (ran on an Intel Atom 1.66ghz with 1gb ram and I know, it sucks):

  • Ternary Operator: 5986 milliseconds or 0.00000005986 seconds per each operator.

  • If-Else: 5667 milliseconds or 0.00000005667 seconds per each statement.

Don't forget that I ran 100 million of them, and I don't think 0.00000000319 seconds difference between the two matters that much.

matthewr
  • 4,679
  • 5
  • 30
  • 40
  • 37
    +1 for those statistics. – Nikhil Agrawal Jul 25 '12 at 05:46
  • 4
    I love that you actually did this! – Keith Jackson Aug 15 '17 at 18:27
  • 3
    I couldn't help but smile at this answer! – Kush Oct 22 '18 at 20:43
  • 2
    I have the complete opposite result. The ternary operator works 2.6 times faster. I tested the same code. My results are: 185ms with ternary and 495ms with if-else statement – Nika Jul 09 '22 at 10:37
  • When you test for such small operators, than don't add in the for-loop itself to the time measurement. Also: using the % operator and also add in this in the time is not a good idea, since divisions are typically very slow operators. – Horitsu Jun 26 '23 at 05:11
25

No.

Use what makes your code readable. If if statements do that, use them. If ternary operators do that, use them.

It is likely that both will compile down to the same IL anyway.

In any event the things that will slow down your application will likely be the database or the network or the hard drive ... anything except whether you used if statements or ternary expressions.

Anthony Mills
  • 8,676
  • 4
  • 32
  • 51
19

There's no reason to expect any difference in performance.

In my opinion, the ternary operator should only be used if all three operands are very concise and easy to read. Otherwise I think it has the potential to make code harder to read.

I think a lot of people mis-use this operator by jamming too much logic into one long line of code. I personally won't use it unless the whole line is less than about 80 characters.

Good:

return isFunky ? funkyValue : null;

Bad:

return (thisThing == thatThing && (anotherThing != null || ! IsThisTrue())) ? someThing.GetThis().GetThat() : yetAnotherThing.GetBlah().GetFoo();

I've seen people do a lot worse than the above. I think they should loose their ternary privileges!

jahroy
  • 22,322
  • 9
  • 59
  • 108
  • 2
    The "bad" exemple wouldn't so bad if you actualy if you write it on 3 different lines. one for the condition, the second line starting with "?" and the lat line starting with ":" and ending with ";" – Maxter Jun 07 '19 at 14:50
9

It is very hard to read ternary operations. If you use nested conditions, understanding ternary will become a overhead. Try to avoid ternary if there are more number of conditions.

3

From my personal point of view, i don't see any performance differences between ternary operator and if statement.Many programming languages supports it and tenary operator is more developer friendly where as conventional If-else operator is understandable in general way.

http://en.wikipedia.org/wiki/%3F%3a

mesimplybj
  • 639
  • 1
  • 5
  • 28