我有两个相同大小的数组和两种方法。
public class Client {
private static int[] ints;
private static final int COUNT = 10000000;
private static Integer[] integers;
public static void main(String[] args) {
Random rand = new Random();
integers = new Integer[COUNT];
for (int i = 0; i < integers.length; i++) {
integers[i] = rand.nextInt();
}
ints = new int[COUNT];
for (int i = 0; i < ints.length; i++) {
ints[i] = rand.nextInt();
}
primitiveToObject();
objectsToPrimitiveToObject();
}
public static void primitiveToObject() {
long start = new Date().getTime();
List<Integer> objects = new ArrayList<>(ints.length);
for (int i = 0; i < ints.length; i++) {
int value = ints[i] + 1;
objects.add(value); //Boxing
}
System.out.println("prim -> object = " + (new Date().getTime() - start));
}
public static void objectsToPrimitiveToObject() {
long start = new Date().getTime();
List<Integer> result= new ArrayList<>(integers.length);
for (int i = 0; i < integers.length; i++) {
int value = integers[i] + 1; //Unboxing
result.add(value); //Boxing
}
System.out.println("obj -> prim -> object = " + (new Date().getTime() - start));
}
}
为什么objectsToPrimitiveToObject()
装箱和拆箱比不拆箱快 10 倍primitiveToObject()
?