本文介绍了清空一个 ArrayList 还是只创建一个新的并让旧的被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

清空一个集合(在我的例子中是一个 ArrayList)与创建一个新集合(并让垃圾收集器清除旧集合)的优缺点是什么?

What are the advantages and disadvantages of emptying a collection (in my case its an ArrayList) vs creating a new one (and letting the garbage collector clear the old one).

具体来说,我有一个名为 listArrayList.当出现某种情况时,我需要清空 list 并重新填充其他内容.我应该调用 list.clear() 还是只创建一个新的 ArrayList 并让旧的被垃圾收集?每种方法的优缺点是什么?

Specifically, I have an ArrayList<Rectangle> called list. When a certain condition occurs, I need to empty list and refill it with other contents. Should I call list.clear() or just make a new ArrayList<Rectangle> and let the old one be garbage collected? What are the pros and cons of each approach?

推荐答案

当你想减少 GC 的负载时,你保留容器并调用 clear:clear()code> 将数组内的所有引用清空,但不会使数组有资格被垃圾收集器回收.这可能会加快未来的插入速度,因为 ArrayList 中的数组不需要增长.当您计划添加到容器中的数据与您清除的数据大小大致相同时,这种方法尤其有利.

You keep the container and call clear when you would like to reduce the load on GC: clear() nulls out all the references inside the array, but does not make the array eligible for reclaiming by the garbage collector. This may speed up future inserts, because the array inside ArrayList does not need to grow. This approach is especially advantageous when the data that you plan to add to the container has roughly the same size as you clearing out.

此外,当其他对象持有对您将要清除的数组的引用时,您可能需要使用 clear.

In addition, you may need to use clear when other objects hold a reference to the array that you are about to clear.

当新数据的大小可能与之前的不同时,释放容器并创建一个新容器是有意义的.当然你也可以通过调用clear()结合trimToSize()来达到类似的效果.

Releasing the container and creating a new one makes sense when the size of the new data may be different from what was there before. Of course you can achieve a similar effect by calling clear() in combination with trimToSize().

这篇关于清空一个 ArrayList 还是只创建一个新的并让旧的被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 02:12