Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is checking whether string.length == 0 still faster than checking string == ""?

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.

like image 343
user1032613 Avatar asked Sep 25 '12 19:09

user1032613


4 Answers

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;
like image 129
Daniel Mühlbachler Avatar answered Nov 04 '22 13:11

Daniel Mühlbachler


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.)

like image 30
Louis Wasserman Avatar answered Nov 04 '22 15:11

Louis Wasserman


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.

like image 7
Chris Gerken Avatar answered Nov 04 '22 15:11

Chris Gerken


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.

like image 1
Ted Hopp Avatar answered Nov 04 '22 13:11

Ted Hopp