Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...