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?
There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.
Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
The only "advantage" is that you can use the ternary operator in an expression (eg. function arguments), making for terser code. using an if , you'd duplicate the full expression.
Conditional or Ternary Operator (?:) in C/C++ The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With