我对自动装箱和性能很好奇,因为我在我的应用程序中做了很多对速度敏感的数学运算,所以我进行了一些测试...
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 会经常发生变化,而且在很大程度上是不可预测的(我说主要是因为它们会保持在一个狭窄的范围内,但我不知道它们会在那个狭窄的范围内做什么),我需要毫秒级的响应时间来对这些数字进行数学运算.
最佳答案
微基准测试很难!我重写了你的基准以使用 caliper :
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.ArrayList;
public class ListsBenchmark extends SimpleBenchmark {
private final ArrayList<Integer> list = new ArrayList<Integer>();
int[] regArray = new int[1];
long total;
@Override
protected void setUp() throws Exception {
list.add(0);
total = 0;
}
public long timeArrayAndPrimitiveType(int reps) {
for (int i = 0; i < reps; i++) {
regArray[0] = i + 10;
if (regArray[0] % 1000 == 0)
total += regArray[0];
}
return total;
}
public long timeListWithAutoboxing(int reps) {
for (int i = 0; i < reps; i++) {
list.set(0, i + 10);
if (list.get(0) % 1000 == 0)
total += list.get(0);
}
return total;
}
public long timeNoAutoboxing(int reps) {
for (int i = 0; i < reps; i++) {
list.set(0, new Integer(i + 10));
if (list.get(0).intValue() % 1000 == 0)
total += list.get(0).intValue();
}
return total;
}
public static void main(String[] args) {
Runner.main(ListsBenchmark.class, new String[]{});
}
}
我没有修改你的原始代码。我发现的是:
- 数组快 3 倍左右
- 创建新的
Integer
稍微快一点(!),也许缓存有一些代价,或者也许这只是我的架构(32 位 Ubuntu,具有 4 个内核和 3 GiB 的内存笔记本电脑)
在图表上(随意自己运行!):
关于java - 列表、基本类型和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462600/