length() 而不是 equals() 来检查 java 中的空字符串

length() instead of equals() to check empty string in java

如果我们使用 length() 而不是 equals() 来检查 java 中的空字符串,代码优化有什么不同吗??

public boolean isEmpty(String str)
{
    return str.equals("");        //NEVER do this
}

public boolean isEmpty(String str)
{
    return str.length()==0;        //Correct way to check empty
}

是真的吗??

您可以使用 str.isEmpty(),它会在内部检查长度。

这是 String class 的实现:

public int length() {
    return count;
}

public boolean isEmpty() {
   return count == 0;
}

可以看到isEmpty()将长度与0进行比较

是的,只检查长度会更快,至少在 OpenJDK 64-Bit Server VM 上是这样。根据我的测量,检查length() == 0只需要equals("")的时间66%左右。

话虽如此,您的程序的低效率几乎肯定存在于其他地方。

内置的 isEmpty 是一个不错的选择。