Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

if statement - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...