Java中两个判断字符串是否为空的方法的执行效率比较,java执行效率,public class
分享于 点击 3897 次 点评:49
Java中两个判断字符串是否为空的方法的执行效率比较,java执行效率,public class
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; }
用户点评