我正在做一项有关大 O 表示法的家庭作业。我们需要创建整数数量不断增加的列表,然后计算对列表进行排序所需的时间以确定是哪个 Big O Collection.sort()。
我编写了一些代码来执行此操作,并生成有关排序方法在每个列表大小的几次迭代过程中花费多长时间的数据。
我能够对 50,000 个整数的列表进行排序,但如果我尝试再次执行完全相同的操作,我将耗尽内存。我认为垃圾收集器应该回收我的内存,所以理论上重复操作应该没有问题。
我读过有关将大型变量设置为 null,并且不在 for 循环 block 之外存储对大型列表的引用的内容。我认为没有理由对我的整数列表的任何引用应该保持 Activity 状态。
我做错了什么,垃圾收集器无法回收我的内存?
private static TreeMap<Integer, ArrayList<Long>> doExperiment(int iterations, int step, int trials, List listType) {
TreeMap<Integer, ArrayList<Long>> results = new TreeMap();
for (int i = 1; i <= iterations; i++) {
// Data size ranges from 1000 - 50,0000 if step = 1000 and iterations = 50
int dataSize = i * step;
ArrayList<Long> trialResults = new ArrayList<Long>();
for (int j = 1; j <= trials; j++) {
// This may be LinkedList, ArrayList depending on the parameter.
List thisList = listType;
// dataSize works up to 50,000 Integers.
Testing t = new Testing(dataSize, thisList);
long nanos = t.timedSort();
// Prints a formatted string to standard output.
processResults(nanos, j, trials, i, iterations);
// The large list exists only within this Testing instance. Set it to null
t = null;
// Please, garbage collection Gods...
System.gc();
}
results.put(dataSize, trialResults);
}
return results;
}
最佳答案
System.gc();
- 不保证启动垃圾收集器
List thisList = listType;
- 复制引用(我猜这是错误的)
因此,当您执行 Testing t = new Testing(dataSize, thisList);
时 - 这实际上与 Testing t = new Testing(dataSize, listType);
您可能想要执行以下操作:List thisList = new ArrayList(listType);
- 是的。这会创建新列表,但在这种情况下,测试将操作新列表,但不会操作同一个列表。
ArrayList<Long> trialResults = new ArrayList<Long>(); // you create new list
....
results.put(dataSize, trialResults); // do you want to put empty list in the result?
关于java - 内存不足 : Java heap space,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098448/