代码优化5-if条件判断的陷阱

最近看到一个公司底层代码中这样写到

public boolean match(FeatureSupportDO f) {
boolean ret = false;
if (null != f) {
if (null != f.getFeature(this.key)
&& (null == this.value
|| this.value.equals(f.getFeature(this.key).getValue()))) {
ret = true;
}
}
return ret;
}

这个if中有两次出现了“f.getFeature(this.key)”,那么java会不会执行两次这个方法呢?
我们写了一个测试类来检测一下:

public class Test {

public static void main(String[] args) {
A a = test.new A("1");
if(a.getP() != null && (1!=1 || a.getP().equals("1"))) {
System.out.println(a.getV());
}
}
class A{
private A a;
private String p;
int v = 0;
public A() {

}

public A(String p) {
this.p = p;
}

public String getP() {
v ++;
return p;
}
public int getV() {
return v;
}
}
}


输出结果是 "2"
这说明if中多次出现的方法,并不会在编译期进行优化,所以当碰到这种情况时,我们做如下修改:

public boolean match(FeatureSupportDO f) {
if (null != f) {
FeatureDO feature = f.getFeature(this.key);
if (null != feature
&& (null == this.value
|| this.value.equals(feature.getValue()))) {
return true;
}
}
return false;
}


当然如果这个getFeature只是简单的return一个属性,那么这个修改的意义并不是很大。
偏偏这个基础类中的方法并非如此,实现中还有递归调用等处理。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值