publicclassArrayCopyTest{ publicstaticvoidmain(String[] args){ finalint N = 10000; finalint M = 5000000; long start, end;
int[] a = newint[N]; for (int i = 0; i < N; i++ ) { a[i] = i; }
start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { int[] b = a.clone(); } end = System.currentTimeMillis(); System.out.println("Object.clone()用时:" + (end - start) + "ms");
start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { int[] c = newint[N]; System.arraycopy(a, 0, c, 0, N); } end = System.currentTimeMillis(); System.out.println("System.arraycopy()用时:" + (end - start) + "ms");
start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { int[] c = newint[N]; for (int j = 0; j < N; j++ ) { c[j] = a[j]; } } end = System.currentTimeMillis(); System.out.println("循环拷贝用时:" + (end - start) + "ms");
start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { int[] c = Arrays.copyOf(a, N); } end = System.currentTimeMillis(); System.out.println("Arrays.copyOf()用时:" + (end - start) + "ms"); } }
publicstaticvoidmain(String[] args){ long a, b, c, d; a = b = c = d = 0; for (int i = 0; i < 10; i++) { a += test1(); b += test2(); c += test3(); d += test4(); } System.out.println("\n************************************\n");
System.out.println("Object.clone()总用时:" + a + "ms"); System.out.println("System.arraycopy()总用时:" + b + "ms"); System.out.println("循环拷贝总用时:" + c + "ms"); System.out.println("Arrays.copyOf()总用时:" + d + "ms"); }
privatestaticlongtest1(){ long start, end; start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { a = newint[N]; int[] b = a.clone(); } end = System.currentTimeMillis(); System.out.println("Object.clone()用时:" + (end - start) + "ms"); return end - start; }
privatestaticlongtest2(){ long start, end; start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { a = newint[N]; int[] c = newint[N]; System.arraycopy(a, 0, c, 0, N); } end = System.currentTimeMillis(); System.out.println("System.arraycopy()用时:" + (end - start) + "ms"); return end - start; }
privatestaticlongtest3(){ long start, end; start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { a = newint[N]; int[] c = newint[N]; for (int j = 0; j < N; j++ ) { c[j] = a[j]; } } end = System.currentTimeMillis(); System.out.println("循环拷贝用时:" + (end - start) + "ms"); return end - start; }
privatestaticlongtest4(){ long start, end; start = System.currentTimeMillis(); for ( int i = 0; i < M; i++ ) { a = newint[N]; int[] c = Arrays.copyOf(a, N); } end = System.currentTimeMillis(); System.out.println("Arrays.copyOf()用时:" + (end - start) + "ms"); return end - start; }