本文介绍了清空一个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).

具体来说,我有一个的ArrayList<矩形> 名为列表。在一定条件下发生,我需要清空列表并与其他内容填充它。我应该叫 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的负荷:清()归零出数组内的所有引用,但不会使阵列资格被垃圾收集器回收。这可能会加快未来的插入,因为里面的的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.

此外,您可能需要使用明确时,其他对象坚持,你是要清除数组的引用。

In addition, you may need to use clear when other objects hold a reference to the array that you are about to 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