Java中两个判断字符串是否为空的方法的执行效率比较的代码

459 阅读1分钟

把写内容过程中比较常用的内容段做个收藏,如下的内容段是关于Java中两个判断字符串是否为空的方法的执行效率比较的内容。

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));  
}  

}

输出结果如下:

str.isEmpty() times: 2735
"".equals(str) times: 10516

其实看下源码很快就发现问题所在

isEmpty()函数的源码

public boolean isEmpty() {
return count == 0;
}

equals的源码

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;
}