Is the conditional operator slow?

I would be curious to know if you are testing this with a Debug or Release build. If it is a debug build, then the difference could quite likely be a difference due to the LACK of low-level optimizations that the compiler adds when you use Release mode (or manually disable debug mode and enable compiler optimizations.)

I would expect with optimizations on, however, that the ternary operator is either the same speed or a bit faster than the if/else statement, while the dictionary lookup is slowest. Here are my results, 10 million warm-up iterations followed by 10 million timed, for each:

DEBUG MODE

   If/Else: 00:00:00.7211259
   Ternary: 00:00:00.7923924
Dictionary: 00:00:02.3319567

RELEASE MODE

   If/Else: 00:00:00.5217478
   Ternary: 00:00:00.5050474
Dictionary: 00:00:02.7389423

I think it is interesting to note here that before optimizations were enabled, ternary computation was slower than if/else, while after, it was faster.

EDIT:

After a bit more testing, in a practical sense, there is little to no difference between if/else and ternary. While the ternary code results in smaller IL, they perform pretty much the same as each other. In a dozen different tests with a release mode binary, the if/else and ternary results were either identical, or off by a fraction of a millisecond for 10,000,000 iterations. Sometimes if/else was slightly faster, sometimes ternary was, but in all practicality, they perform the same.

Dictionary performs significantly worse, on the other hand. When it comes to these kinds of optimizations, I would not waste my time choosing between if/else and ternary if the code already exists. However, if you currently have a dictionary implementation, I would definitely refactor it to use a more efficient approach, and improve your performance by some 400% (for the given function, anyway.)


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.