【日常工作】Java字符串判斷優化

環境:
MacBook Pro 15
jdk8
IntelliJ IDEA
Spring版本:5.0.7.RELEASE

引子:

看Spring AOP源碼,看到5.0.7版本把DefaultAopProxyFactory.class,中的createAopProxy()的判斷邏輯,是通過!進行判斷,考慮和“==”判斷有沒有區別?。

問題:

  1. Java裏Boolean類型的判斷,是否有效率問題?
  2. 字符串判空,如何寫效果更好?

解決:

  1. 最優解:使用!。
  2. 最優解:使用(str==null || str.length() == 0)。

TIPS:

1.看下Spring5.0.7版本中DefaultAopProxyFactory類中的createAopProxy()判斷邏輯:

    public AopProxy createAopProxy(AdvisedSupport advisedSupport) throws AopConfigException {
        if (!advisedSupport.isOptimize() && !advisedSupport.isProxyTargetClass() && advisedSupport.getProxiedInterfaces().length != 0) {
            return new JdkDynamicAopProxy(advisedSupport);
        } else if (!cglibAvailable) {
            throw new AopConfigException("Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.");
        } else {
            return DefaultAopProxyFactory.CglibProxyFactory.createCglibProxy(advisedSupport);
        }
    }

2.看下java.lang.String.java中的isEmpty()方法:

 public boolean isEmpty() {
        return value.length == 0;
    }

 public int length() {
        return value.length;
    }

給大家個簡單原則:源碼咋用就咋用 maff!!!

參考有熱心網友測試對比,基本結論和給大家的原則一致。

參考:

關於JAVA字符串非空判斷效率問題

Java判斷一個字符串str不爲空:方法及時間效率

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章