Why is string.isEmpty() better than using string.equals("") ?
Just look at the source of String#isEmpty()
:
public boolean isEmpty() {
return count == 0;
}
It simply returns the result of comparing count
variable stored as a part of the class with 0
. No heavy computation. The value is already there.
Whereas, the String.equals()
method does lot of computations, viz, typecasting, reference comparison, length comparison - String#equals(Object)
source code. So, to avoid those runtime operations, you can simply use isEmpty()
to check for empty strings.
That would be a slower by a minute difference though.
Note: The Oracle Java 7 version of String.isEmpty()
uses value.length == 0
, as it no more stores the count
and offset
variable. In openjdk-7 though, it still uses the count
variable there.
But still, the value.length
computation will be a bit faster than all those operations in equals()
method.
Apart from the performance difference, which is really not of much concern, and the difference if any would be minute, the String.isEmpty()
method seems more clear about your intents. So, I prefer to use that method for checking for empty strings.
And at last, of course, don't believe on what you see. Just benchmark your code using both the methods, and see for any measurable differences if any.