As far as performance goes: In a fully-compiled language like C or C++, with optimizations on, the difference is probably zero. In other languages (interpreted, byte-code-compiled, or jit-compiled) there may be a difference, but 1. it's not going to be much and 2. it's not going to be your bottleneck. There are exceptions, but those are rare, and if you encounter one of them, you're probably fiddling with fine-grained profiling and instruction-level optimizations; in all the other cases, either is going to be fast enough.
So, as always, your first choice should be to optimize for readability, not for runtime performance. Which brings us to the question when you should use one or the other; well, opinions differ. One camp says the ternary operator simply shouldn't be used at all, for clarity's sake; and they certainly have a point, because it has the tendency to make for really complicated one-liners, especially if you nest it, but also because its precedence can lead to undesirable results. However, I think there are situations where a ternary operator makes the code more readable, and I don't see anything wrong with using it in such a situation; a textbook example is simple text pluralizing:
printf("%i %s deleted.", num_files, (num_files > 1) ? "files" : "file");
The same code written with an explicit if
statement would have taken 5 additional lines without substantially contributing to readability.
That said, IIf
in VB has a nasty caveat: unlike If
, which is a proper language statement and evaluates only one branch, IIf
is a built-in function, so both branches get evaluated, no matter what the condition says. As long as the branches don't have side effects, you won't notice, but when they do, you're in for some serious face-palming.