As a bookmark of some of the most commonly used sections in writing, the following section compares the execution efficiency of two Java methods for determining whether a string is empty.

public class Test4

{

public static void main(String[] args)

{

long times = 999999999;

String str = “”;

    long a1 = System.currentTimeMillis();  
    for (long i = 0; i < times && str.isEmpty(); i++)  
    {  
    }  
    long a2 = System.currentTimeMillis();  
    System.out.println("str.isEmpty() times: " + (a2 - a1));  

    long b1 = System.currentTimeMillis();  
    for (long i = 0; i < times && "".equals(str); i++)  
    {  
    }  
    long b2 = System.currentTimeMillis();  
    System.out.println(""".equals(str) times: " + (b2 - b1));  
}  
Copy the code

}

The following output is displayed:

str.isEmpty() times: 2735

“”.equals(str) times: 10516

In fact, look at the source code quickly found the problem

IsEmpty () function source

public boolean isEmpty() {

return count == 0;

}

Equals the source

public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n– ! = 0) { if (v1[i++] ! = v2[j++]) return false; } return true; } } return false; }