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.
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()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…