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花费的时间比自己遍历还慢了?这是为什么呢???
* 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花费的时间比自己遍历还慢了?这是为什么呢???
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货