原文链接:https://blog.csdn.net/chicaohun7473/article/details/100851373
查看String源码时,读到源码的toString方法时,打算探究下几种转换的效率,网上查到该帖子时,
本地执行后发现结果与帖子并不相同,唯一的区别便是jdk的版本,故提出自己的结论!
测试环境:操作系统 windows 10,内存 8g,jdk 1.8,jvm参数是默认值,测试代码如下:
1 public static void main(String[] args) { 2 Integer[] intArr = new Integer[2000000]; 3 String[] strArr1 = new String[2000000]; 4 String[] strArr2 = new String[2000000]; 5 String[] strArr3 = new String[2000000]; 6 String[] strArr4 = new String[2000000]; 7 Long t1 = System.currentTimeMillis(); 8 for(int i = 0; i < 2000000; i++){ 9 intArr[i] = i + 1; 10 } 11 Long t2 = System.currentTimeMillis(); 12 for(int i = 0; i < 2000000; i++){ 13 strArr1[i] = String.valueOf(intArr[i]); 14 } 15 Long t3 = System.currentTimeMillis(); 16 for(int i = 0; i < 2000000; i++){ 17 strArr2[i] = Integer.toString(intArr[i]); 18 } 19 Long t4 = System.currentTimeMillis(); 20 for(int i = 0; i < 2000000; i++){ 21 strArr3[i] = intArr[i] + ""; 22 } 23 Long t5 = System.currentTimeMillis(); 24 for(int i = 0; i < 2000000; i++){ 25 strArr4[i] = (intArr[i]).toString(); 26 } 27 Long t6 = System.currentTimeMillis(); 28 System.out.println("t1 = " + t1); 29 System.out.println("t2 = " + t2); 30 System.out.println("t3 = " + t3); 31 System.out.println("t4 = " + t4); 32 System.out.println("t5 = " + t5); 33 System.out.println("t6 = " + t6); 34 System.out.println("赋值:" + (t2 - t1)); 35 System.out.println("String.valueOf(i):" + (t3 - t2)); 36 System.out.println("Integer.toString(i):" + (t4 - t3)); 37 System.out.println("i + \"\":" + (t5 - t4)); 38 System.out.println("i.toString():" + (t6 - t5)); 39 }
执行结果:
推荐使用 toString() 或者String.valueOf(i)方法。