关于System.arraycopy效率的质疑

Benjamin_whx 2016-01-17 06:15:15
package Collections;

import java.util.Arrays;

/**
* Created by piqiu on 1/16/16.
*/
public class CollectionsTest {

public static void main(String[] args) {
int source[] = new int[100000000];
Arrays.fill(source, 250);
int destinate[] = new int[100000000];

// useForEach(source, 0, destinate, 0, 100000000); // useForEach spend: 63 millSeconds
useMemocpy(source, 0, destinate, 0, 100000000); // useMemocpy spend: 76 millSeconds
}

private static void useForEach(int[] source, int startSourceIndex, int[] destinate, int startDesIndex, int length) {
long startMillSeconds = System.currentTimeMillis();

int desIndex = startDesIndex;
for (int i = startSourceIndex; i < length; i++) {
destinate[desIndex] = source[startSourceIndex];
desIndex++;
}

long endMillSeconds = System.currentTimeMillis();
System.out.println("useForEach spend: " + (endMillSeconds - startMillSeconds) + " millSeconds");
}

private static void useMemocpy(int[] source, int startSourceIndex, int[] destinate, int startDesIndex, int length) {
long startMillSeconds = System.currentTimeMillis();
System.arraycopy(source, startSourceIndex, destinate, startDesIndex, length);
long endMillSeconds = System.currentTimeMillis();
System.out.println("useMemocpy spend: " + (endMillSeconds - startMillSeconds) + " millSeconds");
}
}



上面的代码我是注释掉一个个运行的,发现数组长度10000000的时候,使用自己遍历来赋值花费5毫秒,使用System.arraycopy花费2毫秒,提升不大。然后我就把数组长度加了一个0,变成1000000000,突然System.arraycopy花费的时间比自己遍历还慢了?这是为什么呢???
...全文
421 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
tanguojingzh 2016-01-18
  • 打赏
  • 举报
回复
你把内容换成中文,你就知道了。英文数字是特殊的
Benjamin_whx 2016-01-17
  • 打赏
  • 举报
回复
不是System.arraycopy效率很高,使用的是内存直接copy的吗?还有是最近java优化了吗,之前for循环没这么效率的啊。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧