What is better? if..else or multiple simple if

前端 未结 5 1697
旧巷少年郎
旧巷少年郎 2020-12-19 08:44

talking about java performance .. what is better? if..else or multiple simple if

if( condition ) {
  some_code;
  return value;
}
else if( condition ) {
  so         


        
5条回答
  •  -上瘾入骨i
    2020-12-19 09:06

    Depends on the situation.

    If the conditions are mutually exclusive, use else. This will cause Java to not check any of the conditions after the one that is found to be true.

    If they are not mutually exclusive, then using a list of if without else could cause multiple cases to occur.

    In your case, with returns in each, the performance will be the same because the same number of comparisons will need to be done no matter what.

提交回复
热议问题