Does string.length == 0 check even faster than string check == ""?

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 am wondering if this statement is true today (or if it has ever been true at all), because I personally think that string == "" is simpler and more readable. I mainly deal with high-level languages ​​such as .NET and java.

+7
source share
5 answers

Typically, a string object retains its length, and therefore getting and comparing an integer is very fast and has less memory access than equals (), where you - in the worst case - need to check the length and loop over characters.

In any case, the string equals () method must also check the length first, and therefore it should be - almost - at the same speed as the length check.

equal to the part in Java (http://www.docjar.com/html/api/java/lang/String.java.html):

 int n = count; if (n == anotherString.count) {...} 

equal to the 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; 
+3
source

The best way to run this test in Java is

 "".equals(string) 

because it handles the case when the string is null.

As for which is faster, I think the answer is that it doesn't matter. Both of them are very fast, and one of them actually most quickly depends on the internal implementation of the compiler.

+6
source

Just use string.isEmpty() .

(I reject "".equals(string) , because if you have a null value, this probably indicates an error that should disable the program because it needs to be fixed. I am intolerant of errors.)

+5
source

You need to be careful when using == to check for equality of strings. If the variable string is not interned, there is 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 would use string.length() == 0 or string.equals("") . A test to find out which is faster.

+1
source

use "".isEmpty() to check for an empty string. Works great and also returns "true" for null objects.

String.isEmpty ()

.equals () throws a NullPointerException if it is zero, which can be annoying.

Also, assuming this is in the Java API, you can probably assume that this is the fastest method.

-one
source

All Articles