我认为isEmpty()更有效率。然而,智能编译器可能会优化equals(“”)调用。从
OpenJDK source:
671 public boolean isEmpty() {
672 return count == 0;
673 }
1013 public boolean equals(Object anObject) {
1014 if (this == anObject) {
1015 return true;
1016 }
1017 if (anObject instanceof String) {
1018 String anotherString = (String)anObject;
1019 int n = count;
1020 if (n == anotherString.count) {
1021 char v1[] = value;
1022 char v2[] = anotherString.value;
1023 int i = offset;
1024 int j = anotherString.offset;
1025 while (n-- != 0) {
1026 if (v1[i++] != v2[j++])
1027 return false;
1028 }
1029 return true;
1030 }
1031 }
1032 return false;
1033 }
还有answer here关于是否使用str.isEmpty()或“”.equals(str)是现成的:
The main benefit of "".equals(s) is you don’t need the null check (equals will check its argument and return false if it’s null), which you seem to not care about. If you’re not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you’re checking, you care whether or not s is empty, not whether it equals the empty string
本文探讨了在Java中检查字符串是否为空的最佳实践。通过对比isEmpty()和equals(“”)两种方法,详细分析了它们的实现原理及性能差异。推荐在不担心null值的情况下使用isEmpty()方法。
448

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



