Possible Duplicate:
Should I use string.isEmpty() or “”.equals(string)?
I am wondering, what difference is there between isEmpty and equals("")? They would appear to be the exact same things to myself.
Possible Duplicate:
Should I use string.isEmpty() or “”.equals(string)?
I am wondering, what difference is there between isEmpty and equals("")? They would appear to be the exact same things to myself.
java.lang.String.isEmpty()
is faster, because it simply compares the length of the string - which is stored in the String object - with zero:
1286 public boolean isEmpty() {
1287 return 0 == count;
1288 }
Using equals("")
performs an actual string comparison - which is supposed to be slower, although the JVM can offset some of its cost. In most implementations it does inlude a length check as well:
854 public boolean equals(Object object) {
855 if (object == this) {
856 return true;
857 }
858 if (object instanceof String) {
859 String s = (String) object;
860 int hash = hashCode; // Single read on hashCodes as they may change
861 int shash = s.hashCode;
862 if (count != s.count || (hash != shash && hash != 0 && shash != 0)) {
863 return false;
864 }
865 for (int i = 0; i < count; ++i) {
866 if (value[offset + i] != s.value[s.offset + i]) {
867 return false;
868 }
869 }
870 return true;
871 }
872 return false;
873 }
Note: Both snippets come from this java.lang.String implementation.
EDIT:
For long-running hot code, the JVM will work out the optimisations in equals("")
and will probably come up with something close to isEmpty()
. For one-shot calls, however, there could be a small performance difference. It's better to just use isEmpty()
and save the JVM from working it out on its own.
In addition, isEmpty()
is also more clear in its intent and, in my opinion, slightly easier to maintain in the long run.
Note that if the string object can also be null
, this is probably better:
if ("".equals(string)) ...
The outcome is the same, but prefer isEmpty()
:
equals("")
gets a different object (from the string pool, so it is not instantiation), and then verifies whether the given string is equal to that stringisEmpty()
simply check whether the number of symbols in the string (stored in the private field count
) is 0. Much less overhead.If there is s possibility that the string can also be null
, you can check apache commons-lang StringUtils.isEmpty(..)
Functionally they're the same (by which I mean they will yield the same result). isEmpty()
is more readable though in my opinion. It's more apparent when you're reading over code. It's also more efficient.
The OpenJDK source uses this implementation of isEmpty
:
public boolean isEmpty() {
return count == 0;
}
Which suggests they would return identical results. Note that equals("")
creates a new string object, so it will be significantly slower than the above simple test.