更好的做法是重新实例化List或调用clear() [英] Better practice to re-instantiate a List or invoke clear()

查看:117
本文介绍了更好的做法是重新实例化List或调用clear()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java(1.6)是否最好在List上调用clear()方法或者只是重新实例化引用?

Using Java (1.6) is it better to call the clear() method on a List or just re-instantiate the reference?

我有一个ArrayList,它是填充了未知数量的对象并定期刷新 - 处理对象并清除列表。刷新后,List再次填满。冲洗是在随机时间发生的。列表中的数字可能很小(对象的10个)或大的(数百万个对象)。

I have an ArrayList that is filled with an unknown number of Objects and periodically "flushed" - where the Objects are processed and the List is cleared. Once flushed the List is filled up again. The flush happens at a random time. The number within the List can potentially be small (10s of Objects) or large (millions of objects).

所以最好让刷新调用清除( )或新的ArrayList()?

So is it better to have the "flush" call clear() or new ArrayList() ?

是否值得担心这类问题或者我应该让VM担心吗?我怎样才能看看Java的内存占用为我自己做这类事情?

Is it even worth worrying about this sort of issues or should I let the VM worry about it? How could I go about looking at the memory footprint of Java to work this sort of thing out for myself?

任何帮助都非常感谢。

推荐答案

需要关注的主要问题是其他代码可能对列表有引用。如果现有列表在其他地方可见,您是否希望该代码看到已清除的列表,或保留现有列表?

The main thing to be concerned about is what other code might have a reference to the list. If the existing list is visible elsewhere, do you want that code to see a cleared list, or keep the existing one?

如果没有其他内容可以看到列表,我' d可能只是清除它 - 但不是出于性能原因;只因为您描述操作声音的方式更像是清除而不是创建新列表。

If nothing else can see the list, I'd probably just clear it - but not for performance reasons; just because the way you've described the operation sounds more like clearing than "create a new list".

ArrayList< T> docs没有指定底层数据结构会发生什么,但是看看Eclipse中的1.7实现,看起来你应该调用 trimToSize() clear()之后 - 否则你仍然可以拥有一个由大量空引用支持的列表。 (当然,这对你来说可能不是问题......也许这比随着大小再次复制而复制数组更有效。你会比我们更了解这个。)

The ArrayList<T> docs don't specify what happens to the underlying data structures, but looking at the 1.7 implementation in Eclipse, it looks like you should probably call trimToSize() after clear() - otherwise you could still have a list backed by a large array of null references. (Maybe that isn't an issue for you, of course... maybe that's more efficient than having to copy the array as the size builds up again. You'll know more about this than we do.)

(当然创建新列表不需要旧列表将所有数组元素设置为null ...但我怀疑在大多数情况下这将是重要的。)

(Of course creating a new list doesn't require the old list to set all the array elements to null... but I doubt that that will be significant in most cases.)

这篇关于更好的做法是重新实例化List或调用clear()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆