原始 Array 和 ArrayList 在性能方面有很大差异吗?
我正在接收 XML,需要转换为原始数组或 ArrayList。
内存和垃圾回收方面的性能有很大差异吗?
我的应用程序每秒将创建数千个这样的对象,并且我需要最大限度地减少 GC,因为我需要实时性能。
I am receiving XML and need to convert to either a primitive Array or ArrayList
.
Is there much difference in terms of performance in terms of memory and garbage collection?
My application will be creating thousand of these objects every second and I need to minimize GC as I need real-time performance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
原始数组效率更高,因为它们不需要包装对象。 Guava 具有由原始数组支持的 List 实现(例如:
Ints.asList(int[])
),也许这对您来说可能是一个合理的解决方案:获得集合的功能,但仅在实际时使用对象需要他们。Primitive arrays are much more efficient, as they don't require wrapper objects. Guava has List implementations that are backed by primitive arrays (example:
Ints.asList(int[])
), perhaps that could be a reasonable solution for you: get the power of a collection but only use Objects when you actually need them.原始数组总是更高效,但高效程度取决于用例的具体细节。最近,我通过在最内部的循环中删除 ArrayList 并用原始数组替换它们,将性能提高了 7 倍。用例是应用于长度为 100-1000 个字符的列表的 O(n^2) 算法。然后我做了一个对照实验,比较了 int[] 数组和 ArrayList 的性能,有趣的是,随着数组/列表大小变大,JIT 编译器似乎开始起作用,性能损失变得少了很多(仅〜20%)。但对于小于 500 的列表大小,ArrayList 的性能损失可能高达 10 倍。因此,如果您有一个经常调用的方法,该方法正在操作大量小列表或数组(就像我的用例一样) ),使用原始数组会对性能产生很大的影响。
Primitive arrays are always more efficient, but by how much depends on the exact details of your use case. I've recently sped up performance by a factor of 7, by ripping out the ArrayLists, and replacing them with primitive arrays, in the inner-most loops. The use case was an O(n^2) algorithm applied to lists 100-1000 characters long. I then did a controlled experiment, comparing the performance of a int[] array to a ArrayList, and interestingly, as the array/list sizes get bigger, the JIT compiler seems to kick in, and the performance penalty becomes a lot less (only ~20%). But for list sizes less than 500, the performance penalty of an ArrayList can be up to a factor of 10. So if you've got a frequently called method, which is manipulating lots of small lists or arrays (as was with my use case), using primitave arrays can have a big performance impact.
正如 Sean Patrick Floyd 指出的那样,原始数组效率更高。
然而,在某些情况下,人们肯定会更喜欢集合。但只要你只是迭代对象,就不需要集合。
As Sean Patrick Floyd pointed out, primitive arrays are much more efficient.
However, there are cases where one would definitely prefer Collections. But as long as you just iterate over the Objects, there is no need for Collections.
链表适合插入/删除,数组适合随机访问。
Linked lists are good for inserts/deletes, and arrays are good for random access.