我应该使用 string.isEmpty ()还是“”. equals (string) ?

我通常与 string == null一起测试它,所以我并不真正关心空安全测试。我应该使用哪个?

String s = /* whatever */;
...
if (s == null || "".equals(s))
{
// handle some edge case here
}

或者

if (s == null || s.isEmpty())
{
// handle some edge case here
}

关于这一点——除了 return this.equals("");或者 return this.length() == 0;isEmpty()还能做其他的事情吗?

222468 次浏览

没关系,我认为 "".equals(str)更清楚。

isEmpty()返回 count == 0;

"".equals(s)的主要好处是你不用 需要检查空值(equals会检查它的参数,如果它是空值就返回 false) ,这点你似乎并不关心。如果你不担心 s为空(或者正在检查它) ,我肯定会使用 s.isEmpty(); 它会准确地显示你正在检查的内容,你关心的是 s是否为空,而不是它是否等于空字符串

除了上面提到的其他问题之外,您可能还需要考虑的一件事情是,isEmpty()是在1.6中引入的,因此如果您使用它,您将无法在 Java 1.5或更低版本上运行代码。

String.equals("")实际上比 isEmpty()调用稍慢一些。字符串存储在构造函数中初始化的 count 变量,因为字符串是不可变的。

isEmpty()将 count 变量比较为0,而 equals 将检查类型、字符串长度,然后在字符串上迭代,以便在大小匹配时进行比较。

所以回答你的问题,isEmpty()实际上会做得少很多! 这是一件好事。

可以使用 apache commons StringUtils isEmpty ()或 isNotEmpty ()。

我编写了一个 Tester类来测试性能:

public class Tester
{
public static void main(String[] args)
{
String text = "";


int loopCount = 10000000;
long startTime, endTime, duration1, duration2;


startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.equals("");
}
endTime = System.nanoTime();
duration1 = endTime - startTime;
System.out.println(".equals(\"\") duration " +": \t" + duration1);


startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.isEmpty();
}
endTime = System.nanoTime();
duration2 = endTime - startTime;
System.out.println(".isEmpty() duration "+": \t\t" + duration2);


System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
}
}

我发现使用 .isEmpty()只花了 .equals("")一半的时间。