Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

java - Empty an ArrayList or just create a new one and let the old one be garbage collected?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...