关于JAVA字符串非空判断效率问题
字符串非空的判断,我们经常如下这样写:
1
if
(str
==
null
||
""
.equals(str)){
2
//
具体操作
3
}
JDK的equals方法的源代码:
1
public
boolean
equals(Object anObject) {
2
if
(
this
==
anObject) {
3
return
true
;
4
}
5
if
(anObject
instanceof
String) {
6
String anotherString
=
(String)anObject;
7
int
n
=
count;
8
if
(n
==
anotherString.count) {
9
char
v1[]
=
value;
10
char
v2[]
=
anotherString.value;
11
int
i
=
offset;
12
int
j
=
anotherString.offset;
13
while
(n
--
!=
0
) {
14
if
(v1[i
++
]
!=
v2[j
++
])
15
return
false
;
16
}
17
return
true
;
18
}
19
}
20
return
false
;
21
}
如果去比较字符串的长度是否为0的话,效率是更高的,str.length()的方法,则是直接返回其大小.
所以做字符串非空判断尽量写成如下方式:
1
if
(str
==
null
||
str.length()
==
0
){
2
//
具体操作
3
}
也可以用apache-common-lang包下StringUtils.isEmpty(String src);方法判断即可,里面的实现就是用长度来判断的。
本文探讨了JAVA中字符串非空判断的不同方法及其效率对比。通过分析JDK源代码揭示了为何使用长度判断更为高效,并推荐了一种更优的判断方式及第三方库方法。
997

被折叠的 条评论
为什么被折叠?



