◎筱米加步枪◎.Blog

Happy coding

关于字符串非空判断效率问题

做一个字符串非空的判断,我们经常如下这样写:

1
2
3
if(str == null || "".equals(str)){
    //具体操作
}

这是一种很正常的写法,但是如果去比较字符串的长度是否为0的话,效率是更高的。贴个JDK的equals方法的源代码:

equals
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean equals(Object anObject) {
if (this == anObject) {
    return true;
}
if (anObject instanceof String) {
    String anotherString = (String)anObject;
    int n = count;
    if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n-- != 0) {
        if (v1[i++] != v2[j++])
        return false;
    }
    return true;
    }
}
return false;
}

再来看看str.length()的方法,则是直接返回其大小。两个对比,很明显的length()方法要优化很多。

所以做字符串非空判断尽量写成如下方式:

equals
1
2
3
if(str == null || str.length() == 0){
    //具体操作
}

其实也可以用apache-common-lang包下StringUtils.isEmpty(String src);方法判断即可,里面的实现就是用长度来判断的。

经理透露,很多笔试面试题经常都会考这样的问题,如果你用equals来判断,那么在面试官的印象就要大大折扣啦。