测试 str.isEmpty()和 “”.equals(str)两种判断的效率
比较次数999999999
str.isEmpty()用时2735(2.7秒)
“”.equals(str)用时10516(10秒)
差别如此之大
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++) { // System.out.println(str.isEmpty()); } 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++) { // System.out.println("".equals(str)); } 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; }