好奇心和效率是这个问题的原因。在某些循环运行后,我正在创建许多新的哈希集:
HashSet 当前在类的顶部这样声明:
private Set<String> failedTests;
然后在代码的后面,只要我重新运行测试,我就创建一个新的 failedTests HashSet:
failedTests = new HashSet<String>(16384);
我一遍又一遍地这样做,这取决于测试的大小。我希望垃圾收集器能够最有效地处理旧数据。但是,我知道另一种选择是在开始时创建 HashSet:
private Set<String> failedTests = new HashSet<String>(16384);
然后每次循环清空HashSet。
failedTests.clear();
我的问题是,在开销等方面,哪种方法最有效?我不知道 clear() 函数在里面做什么——它是在做同样的事情,将旧数据发送到垃圾收集器,还是在做一些更有效率的事情?此外,我为 HashSet 提供了较大的初始容量缓冲,但如果测试需要超过 2^14 个元素,.clear()
函数是否会将 HashSet 重新实例化为 16384?
要添加,我找到了 source code to clear() here .所以它至少是最坏情况下的 O(n) 操作。
使用 clear 函数,我做了一个在 565 秒内完成的测试过程。 使用GC处理,测试在506秒内完成。
但这不是一个完美的基准,因为还有其他外部因素,例如与计算机和网络文件系统的接口(interface)。但是整整一分钟确实感觉很好。有没有人推荐一个可以在行/方法级别工作的特定分析系统? (我正在使用 Eclipse Indigo)
最佳答案
I don't know what the clear() function is doing inside
它正在调用内部使用的 HashMap
表的 clear()
方法。在 HashMap
中,clear()
方法定义如下:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
is it doing the same thing, sending the old data to the garbage collection, or is it doing something even more efficient?
tab[i] = null
指出它使旧数据符合垃圾收集条件。
Also, I am giving the HashSet a large cushion of initial capacity, but if a test requires more than 2^14 elements, will the .clear() function re-instantiate the HashSet to 16384?
不,不会。
which is the most efficient way of doing this in terms of overhead, etc?
我想,Java 垃圾收集器知道如何以最有效的方式完成它的工作。所以让垃圾收集器来处理这个。所以,我更愿意在每次需要时创建一个新的失败测试 HashSet
。
关于java - 清除 HashSet 与创建新 HashSet 的内存效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17155664/