67,514
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args){
final int LENGTH=20000000;
int[] s=new int[LENGTH];
int[] s2=new int[LENGTH];
for(int i=0;i<LENGTH;i++){
s[i]=i;s2[i]=i;
}
System.out.println("测试for循环:");
long st1=System.currentTimeMillis();
for(int i=1;i<LENGTH;i++){
s[i]=s2[i];
}
long ed1=System.currentTimeMillis();
System.out.println(ed1-st1);
System.out.println("测试copy循环:");
long st2=System.currentTimeMillis();
System.arraycopy(s,1,s,0,s.length-1);
long ed2=System.currentTimeMillis();
System.out.println(ed2-st2);
System.out.println("测试copy循环:");
st2=System.currentTimeMillis();
System.arraycopy(s,1,s2,0,s.length-1);
ed2=System.currentTimeMillis();
System.out.println(ed2-st2);
String[] srcArray = new String[1000000];
String[] forArray = new String[srcArray.length];
String[] arrayCopyArray = new String[srcArray.length];
//初始化数组
for(int index = 0 ; index < srcArray.length ; index ++){
srcArray[index] = String.valueOf(index);
}
long forStartTime = System.currentTimeMillis();
for(int index = 0 ; index < srcArray.length ; index ++){
forArray[index] = srcArray[index];
}
long forEndTime = System.currentTimeMillis();
System.out.println("for方式复制数组:" + (forEndTime - forStartTime));
long arrayCopyStartTime = System.currentTimeMillis();
System.arraycopy(srcArray,0,arrayCopyArray,0,srcArray.length);
long arrayCopyEndTime = System.currentTimeMillis();
System.out.println("System.arraycopy复制数组:" + (arrayCopyEndTime - arrayCopyStartTime));
}
我跑了很多次,int数组的效率有时for高,有时arraycopy高。
但是String数组,每次都是arrayCopy高,我在想,是不是arrayCopy在处理引用类型时,只拷贝了其引用导致的?就是都是浅拷贝导致的?
https://blog.csdn.net/wangyangzhizhou/article/details/79504818 System.out.println("测试for循环:");
long st1=System.currentTimeMillis();
for(int i=10000;i<200000000;i++){
s[i-1]=s[i-1];
}
System.out.println("测试copy循环:");
long st2=System.currentTimeMillis();
System.arraycopy(s,1,s,0,s.length-1);
long ed2=System.currentTimeMillis();
System.out.println(ed2-st2);