java if 直接return,Java: if-return-if-return vs if-return-elseif-return

Neither one is more efficient than the other. The compiler can easily see that the two are identical, and in fact Suns/Oracles javac produces identical bytecode for the two methods.

Here is an IfTest class:

class IfTest {

public boolean eq1(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

return true;

}

public boolean eq2(Object obj) {

if (this == obj)

return true;

else if (obj == null)

return false;

else if (getClass() != obj.getClass())

return false;

return true;

}

}

I compiled it with javac and the disassembly is as follows:

public boolean eq1(java.lang.Object);

Code:

0: aload_0

1: aload_1

2: if_acmpne 7

5: iconst_1

6: ireturn

7: aload_1

8: ifnonnull 13

11: iconst_0

12: ireturn

13: aload_0

14: invokevirtual #2; //Method Object.getClass:()Ljava/lang/Class;

17: aload_1

18: invokevirtual #2; //Method Object.getClass:()Ljava/lang/Class;

21: if_acmpeq 26

24: iconst_0

25: ireturn

26: iconst_1

27: ireturn

public boolean eq2(java.lang.Object);

Code:

0: aload_0

1: aload_1

2: if_acmpne 7

5: iconst_1

6: ireturn

7: aload_1

8: ifnonnull 13

11: iconst_0

12: ireturn

13: aload_0

14: invokevirtual #2; //Method Object.getClass:()Ljava/lang/Class;

17: aload_1

18: invokevirtual #2; //Method Object.getClass:()Ljava/lang/Class;

21: if_acmpeq 26

24: iconst_0

25: ireturn

26: iconst_1

27: ireturn

That is, I would recommend using the first version (without the else). Some people may argue that it's cleaner with the else parts, but I would argue the opposite. Including the else indicates that the programmer didn't realize that it was unnecessary.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值