我对自动装箱和性能很好奇,因为我在我的应用程序中做了很多对速度敏感的数学运算,所以我进行了一些测试......
public static void main(String[] args) {
// Some initialization so I know it's not involved
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0);
int[] regArray = new int[1];
long total = 0;
// This one uses an array and primitive type
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
regArray[0] = i + 10;
if (regArray[0] % 1000 == 0) total += regArray[0];
}
System.out.println("Runtime in millis: " + (System.currentTimeMillis() - start));
System.out.println(total);
// This one autoboxes, but still uses the Object type because it's a list
total = 0;
start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
list.set(0, i + 10);
if (list.get(0) % 1000 == 0) total += list.get(0);
}
System.out.println("Runtime in millis: " + (System.currentTimeMillis() - start));
System.out.println(total);
// This one doesn't autobox
total = 0;
start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
list.set(0, new Integer(i + 10));
if (list.get(0).intValue() % 1000 == 0) total += list.get(0).intValue();
}
System.out.println("Runtime in millis: " + (System.currentTimeMillis() - start));
System.out.println(total);
}
这是一个示例输出:
Runtime in millis: 78
50005000000
Runtime in millis: 250
50005000000
Runtime in millis: 250
50005000000
这似乎表明我应该远离List<>
数学,速度敏感的应用程序和子类。你同意吗,stackoverflow?
编辑:我的实际用例是我需要存储几百个int
s 和float
s ,它们会经常且很大程度上不可预测地变化(我说主要是因为它们会保持在一个狭窄的范围内,但我不知道他们会在那个范围内做什么范围窄),我需要对这些数字进行数学运算时需要毫秒级的响应时间。