I read from a programming book about 7-8 years ago that checking string.length == 0
is a faster way to check for empty strings. I'm wondering if that statement still holds true today (or if it has ever been true at all), because I personally think string == ""
is more straightforward and more readable. I mostly deal with high-level languages such as .NET and java.
Usually, string object store their length and therefore getting and comparing the integer is very fast and has less memory access than an equals() where you - in the worst case - have to check the length and loop over the characters.
Anyway, nowadays the equals() method of a string should also check for the length first and therefore it should be - nearly - the same speed as checking for the length.
equals part in Java (http://www.docjar.com/html/api/java/lang/String.java.html):
int n = count;
if (n == anotherString.count) {...}
equals part in Objective-C (http://www.opensource.apple.com/source/CF/CF-476.15/CFString.c) - NSString is based on CFString:
if (len1 != __CFStrLength2(str2, contents2)) return false;
Just use string.isEmpty()
.
(I reject "".equals(string)
because if you have a null, that probably indicates a bug that should crash the program because it needs to be fixed. I'm intolerant of nulls.)
The best way to do that test in Java is
"".equals(string)
because that handles the case where string is null.
As for which is faster, I think the answer is that it doesn't matter. Both are very fast and which one is actually fastest depends on internal compiler implementation.
You need to be careful about using ==
to test for string equality. If the variable string is not interned, there's a good chance that the test will fail.
String a = "abc";
String b = a.substring(3);
System.out.println("b == \"\": " + (b == "")); // prints false
System.out.println("b.equals(\"\"): " + b.equals("")); // prints true
I'd use string.length() == 0
or string.equals("")
. Benchmark to see which is faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With