Is the conditional operator slow?

Very odd, perhaps .NET optimization is backfireing in your case:

The author disassembled several
versions of ternary expressions and
found that they are identical to
if-statements, with one small
difference. The ternary statement
sometimes produces code that tests the
opposite condition that you would
expect, as in it tests that the
subexpression is false instead of
testing if it is true. This reorders
some of the instructions and can
occasionally boost performance.

http://dotnetperls.com/ternary

You want might consider the ToString on the enum value (for the non-special cases):

string keyValue = inKey.ToString();
return shift ? keyValue : keyValue.ToLower();

EDIT:
I’ve compared the if-else method with the ternary operator and with 1000000 cycles the ternary operator is always at least as fast as the if-else method (sometimes a few millisec faster, which supports the text above). I think that you’ve made somekind of error in measuring the time it took.

Leave a Comment