Possible Duplicate:
Java: If vs. Switch
For all the conditional statements that are observed in programming, which of these blocks is the most preferred:
- Ternary operator
- else-if block
- switch block
Thanks in advance!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Of course you may implement the comparison in different ways.
I did it this way:
common block:
if:
case:
Ternary:
They don’t compile to the same bytecode:
However, advantages of switch come into play when you have multiple cases – not just 2.
If and ternary get cascading for more than 2 cases.
But they differ idiomatically/semantically. The Ternary operator returns something, but not the if or the switch.
So it isn’t that clear what you have to compare.
But I made a benchmark with following result:
Which shows, that they really don’t make much difference, and that caching effects have still, for 5 M cases, an influence, even after heating up the VM.
In real circumstances, you rarely have million invocations where nearly nothing happens. But if something happens, the time for if/case/ternary becomes soon irrelevant.
Here is the code I tested:
Here is the Testing code (which is Scala):
updated:
And here is the BenchCoat source