Nested if else vs switch in JAVA [duplicate] - java

I'd like to know if there is any efficiency difference between using if statement or switch. For example:
if(){
//code
}
else if(){
//code
}
else{
//code
}
I believe that program needs to go and check all of the if statement even if the first if statement was true.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?

Switch perf is better than if else as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
With switch the JVM loads the value to compare and iterates through
the value table to find a match, which is faster in most cases

Switch is faster.
Imagine you are at an intersection, with many paths.
With switch, you go to the right path at the first time.
With if, then you have to try all the paths before you find the right one.
Use switch whenever possible.
Of course, for computer this difference is very small that you don't even notice. But yeah, you get the point.

I think the code is quite clear. With if, you have to check each case and after case by case (in the worst case, last return gives back the result). With switch, some kind like a special byte code checking and jump to the correct case to return. So the switch is a bit faster than the if statement. However, I think we need to focus on the way we implement for easier to read. In some simple case, the if is also a choice to write code.

Related

Java switch use case

I'm reluctant to use a switch, but I saw switch will be improved in Java 12
Java 12 added the switch expression as an experimental feature. A Java switch expression is a switch statement which can return a value.
The only use case I found (before Java 12) where switch may be useful is returning different values from a small closed set of cases, e.g.:
switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}
Or in Java 12 example:
return
switch(digitInDecimal){
case 0 -> '0';
case 1 -> '1';
case 2 -> '2';
default -> '?';
But I found an old but high-ranked answer that says to avoid multiple return statements:
Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.
So I wonder, is that answer still relevant due to switch changes?
Must I wait for Java 12 where switch can be used without temporary variables and breaks?
Assigning a value to a local variable and then returning that at the end is considered a good practice.
I have no idea when it was considered a good practice. To me, switch is usually * an indicator that a design error was made. I would rather put my effort into thinking how to avoid a switch than into wondering how to return a value from a switch.
A few examples
Long list of if statements in Java
How to avoid switch-case statements in Java
Converting many 'if else' statements to a cleaner approach
Methods having multiple exits are harder to debug and can be difficult to read.
The same goes for a method that has a lot of breaks - that's what you are going to do if you choose the "local-variable approach".
In my opinion, none of these
// 1
switch (input) {
case "A":
return "1";
case "B":
return "2";
default:
return "0";
}
// 2
String varibleToReturn = null;
switch (input) {
case "A":
varibleToReturn = "1";
break;
case "B":
varibleToReturn = "2";
break;
default:
varibleToReturn = "0";
}
return varibleToReturn;
// 3
return switch(digitInDecimal) {
case 0 -> '0';
case 1 -> '1';
case 2 -> '2';
default -> '?';
}
makes a significant difference, or a slight improvement. Yes, Java-12's switch would give more conciseness and expressiveness, but the fundamental idea remains the same.
Must I wait for Java 12 where switch can be used without temporary variables and breaks?
What does it mean? :) No, the deadline is tomorrow, you have to work with what you've got at hand now.
*I am not underestimating the usefulness of switch. It may come in handy, for instance, when you programme at low-level, or you write an optimization.
I am just saying that in the real world, with Springs, and Hibernates, in a world of patterns, switch is obsolescent.
But I found an old but high-ranked answer that says to avoid multiple
return statements:
Assigning a value to a local variable and then returning that at the
end is considered a good practice. Methods having multiple exits are
harder to debug and can be difficult to read.
So I wonder, is that answer still relevant due to switch changes?
This is a common misconception, it originates form the phrase: "Single entry, single exit." (Page 24) All this originates from an other era, one that lead to structured programming languages and eventually to object oriented programming languages (like Java).
Don't worry about multiple return statements, there is nothing wrong with it.

Cyclomatic Compleity IF ELSE vs SWITCH CASE

Many code analysis tools like sonar throw errors for switch case if used instead of multiple is-else for cyclomatic complexity . Is there a number which should be a threshold of when one should use if else and when one should use switch case ?
Say if its a case of 50 , to reduce cyclomatic complexity one should use switch case ? Would be good if you could support your answer with an example ?
To answer the question with another question.
Would you rather read:
if(cond1)..
else if(cond2)...
else if(cond50)...
else ...
or
value = map.get(key)
If there are so many possible cases, than neither the switch or if seem appropriate and should therefore be replaced with key-value structure or state machine pattern - if branching is really complicated.
You can find an example implementation here:
fsm
As to when to use if or switch, keep in mind that switch cannot accept the following types:
long, double, float, boolean so when you have such an input, switch is obviously not a choice.
I wouldn't use number as a metric to use switch or if statement. There is one exception however, if an input can have only 2 possible values it is better to use if. Even Sonar should suggest you this.
That said, switch is usually more readable than the series of if statements. As an important decision factor, other than readability, within switch statement there can be groups of values which might require same execution path. It is basically safer version of the goto. Unlike if, where each outcome is usually bound to specific execution path.

if else vs switch performance in java

I'd like to know if there is any efficiency difference between using if statement or switch. For example:
if(){
//code
}
else if(){
//code
}
else{
//code
}
I believe that program needs to go and check all of the if statement even if the first if statement was true.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?
Switch perf is better than if else as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
With switch the JVM loads the value to compare and iterates through
the value table to find a match, which is faster in most cases
Switch is faster.
Imagine you are at an intersection, with many paths.
With switch, you go to the right path at the first time.
With if, then you have to try all the paths before you find the right one.
Use switch whenever possible.
Of course, for computer this difference is very small that you don't even notice. But yeah, you get the point.
I think the code is quite clear. With if, you have to check each case and after case by case (in the worst case, last return gives back the result). With switch, some kind like a special byte code checking and jump to the correct case to return. So the switch is a bit faster than the if statement. However, I think we need to focus on the way we implement for easier to read. In some simple case, the if is also a choice to write code.

Help with switch statement

I am relatively new to java. In a switch statement, do you have to put a break statement after each case?
No, you don't have to. If you omit the break statement, however, all of the remaining statements inside the switch block are executed, regardless of the case value they are being tested with.
This can produce undesired results sometimes, as in the following code:
switch (grade) {
case 'A':
System.out.println("You got an A!");
//Notice the lack of a 'break' statement
case 'B':
System.out.println("You got a B!");
case 'C':
System.out.println("You got a C.");
case 'D':
System.out.println("You got a D.");
default:
System.out.println("You failed. :(");
}
If you set the grade variable to 'A', this would be your result:
You got an A!
You got a B.
You got a C.
You got a D.
You failed. :(
You don't have to break after each case, but if you don't they will flow into each other. Sometimes you want to bundle multiple cases together by leaving out the breaks.
It is better you do. Otherwise the next statements will be executed too.
switch(someNumber) {
case thisCaseMatches:
doThat();
case thisCaseDoesNotMatch:
shouldntExecuteYetItWillBeExecuted();
default:
alsoWillbeExecuted();
}
You do if you are not exiting the switch statement with a return or other action.
Semantically yes. Otherwise all case statements after the first matching one would run.
It's a good practice to put break after each statement.
You're not forced.
But if you don't put breaks tatement you've cascade switch statement, namely more condition could be matched, and sometimes this can lead to logical errors.
However there are people which think that cascade statements can optimize the code, helping to write less code.

case-statement or if-statement efficiency perspective [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is "else if" faster than "switch() case"?
What is the relative performance difference of if/else versus switch statement in Java?
I know that case statements can be implemented with jump tables. Does this make them more efficient than if statements?
Is this just micro-optimization that should be avoided?
I think the main thing is to write the code as clearly as possible. Micro-optimizations like this shouldn't be the focus.
For example, if you have something like this:
if (age == 10) {
// ...
} else if (age == 20) {
// ...
} else if (age == 30) {
// ...
} else if (age == 40) {
// ...
}
Then it's clearer to use a switch statement:
switch (age) {
case 10:
// ...
break;
case 20:
// ...
break;
case 30:
// ...
break;
case 40:
// ...
break;
}
Again, I would focus on making the code easiest to read and maintain rather than nano-second level efficiency gains.
Any compiler will make the jump table if it can verify that the values are reasonably compact. (I doubt if they are in this case, being multiples of 10.)
This is a micro-optimization. Micro-optimization makes sense only if you know that it does. Typically, there are larger "fish to fry" elsewhere, in the form of function calls that could be done without. However, if you have already tuned the daylights out of this code, and your profiling shows that a good fraction (like 10% or more) of time is going into these IF statements (and not to their contents) then it helps. This can happen, for example, in a byte-code interpreter.
Added: Another reason I like to use switch is, even if it doesn't make a jump table - when stepping through the code in a debugger, it goes directly to the proper case, rather than making me step through a lot of false if statements. Makes it easier to debug.
If you had a very large chain of if else statements, then, yes, you might feel the difference. But it is very unrealistic that you'll ever write such a long ifelse chain. And if even you did, it's still very unlikely that that is where your performance bottleneck would be.
Write your code to be readable first, and let yourself be guided by a profiler when the need for performance optimization arises.
Probably is doen't matter. Bytecode is just a "transport format" to the JVM. What happens insite the JVM is very different from the bytecode representation. (Example: Bytecode doesn't offer float operations, so float +-*/% float is done as double operations and then the result is casted back to float. Same is true for byte/short, they are converted to int and then back.) But for switch they are two bytecode formats, one already with a jump table. But honestly: I would choose a format which is best for you and the reader of your program. The JVM will do the rest. If you are too smart you JVM maybe don't get your point and in the end the program is slower.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" D. Knuth
Yes
No, it is part of your program design. But you should consider whether an over-ridable method mightn't be an even better solution, with a family of types.

Categories

Resources