何苦用的ArrayList(INT容量)? [英] Why bother using ArrayList(int capacity)?

查看:98
本文介绍了何苦用的ArrayList(INT容量)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以pretty每多ArrayList中有关能力的问题是如何使用它,或者(奇怪)访问它,我很熟悉的信息。我很感兴趣,它是否真的值得使用ArrayList的构造函数,如果你碰巧知道或有一个大概的了解有多少项目将在ArrayList中,设置容量?

So pretty much every question related to capacity in ArrayList is how to use it or (oddly) access it and I am quite familiar with that information. What I am interested in whether it is actually worth using the ArrayList constructor that sets capacity if you happen to know or have a rough idea how many items will be in the ArrayList?

有没有比较需要多长时间只使用天真的元素添加到一个ArrayList与任何COM prehensive基准pre-设置一个ArrayList的容量?

Are there any comprehensive benchmarks comparing how long it takes to just use naive adding of elements to an ArrayList versus pre-setting the capacity of an ArrayList?

推荐答案

显然,对于任何特定的应用程序,你不得不测试任何性能调整,以确定他们是否实际上是优化(如果它们实际上是必要的),但也有一些时候,明确设置容量可以是值得的。例如:

Obviously for any specific application you'd have to test any performance adjustments to determine if they are in fact optimizations (and if they are in fact necessary), but there are some times that setting the capacity explicitly can be worthwhile. For example:


  • 您正在创建一个非常大的数字数组列表,其中大部分将是非常小的。在这种情况下,你可能要设置的初始容量很低,和/或修剪时,你就大功告成了填充一个给定的数组的能力。 (在这种情况下,最优化小于速度比存储器使用的问题。但是请注意,该列表自身具有内存开销一样,它包含的阵列,因此,在这种情况下,它很可能是更好的重新设计以这样的方式,以具有较少的列表。)

  • 您正在创建的数组列表的非常的大已知大小,和你想的时候添加的每个的元素是非常小的(也许是因为每次您添加元素,你要发送到外部数据源的一些反应)。 (缺省的几何式增长需要的摊销的恒定时间:每周一次的同时,一个巨大的处罚发生,使得整体平均业绩是完全没问题的,但如果你关心个人的插入采取单独,即可能还不够好。)

  • You're creating a very large number of array-lists, most of which will be very small. In this case, you might want to set the initial capacity very low, and/or to trim the capacity whenever you're done populating a given array. (In this case, the optimization is less a matter of speed than of memory usage. But note that the list itself has memory overhead, as does the array it contains, so in this sort of situation it's likely to be better to redesign in such a way as to have fewer lists.)
  • You're creating an array-list of a very large known size, and you want the time to add each element to be very small (perhaps because each time you add an element, you have to send some response to an external data-source). (The default geometric growth takes amortized constant time: every once in a while, a massive penalty is incurred, such that the overall average performance is completely fine, but if you care about individual insertions taken individually, that might not be good enough.)

这篇关于何苦用的ArrayList(INT容量)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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