JDK8 performance of ArrayList compared to LinkedList

六眼飞鱼酱① 提交于 2021-01-29 03:30:32

问题


I am starting to see more and more benchmarks that demonstrate ArrayList crushing LinkedList in terms of performance for 'large' inserts example below: Gluelist

Adding(1M) Elements (5 Tests Avg.)

LinkedList: 174.8 milliseconds
ArrayList:  76.4 milliseconds
GlueList:   39.2 milliseconds

Adding(10M) Elements (5 Tests Avg.)

LinkedList: 8975.6 milliseconds
ArrayList:  4118.2 milliseconds
GlueList:   3320.1 milliseconds

I ran similar tests on a RHEL 7.2 with JDK8.latest and saw similar results. I am under the impression that a LinkedList insert is O(1) even in the worst case and an ArrayList takes > O(1) because of the copy operation (I realize that we can discuss amortized costs, but that is out of scope). My question is this: How is LinkedList performing worse than ArrayList given that ArrayList forces a copy operation when capacity is nearly reached?


回答1:


They have the same big O but that doesn't tell you about the constant relationship. It tells you how they behave on an idealised machine, not a real machine.

LinkedList allocates and uses more memory. It creates a 24 byte object per node where as an ArrayList uses 4 bytes (usually) per reference and creates far less objects.




回答2:


Big O doesn't really help you there. It tells you in what direction growth goes, but it doesn't give you absolute numbers.

ArrayList uses arrays, with highly optimized native System.arrayCopy() calls.

LinkedLists have to create a wrapper object for every single node and store pointers to the next and previous nodes in it. That takes time.

ArrayList does not create a single object when inserting, unless it resizes the array, which doesn't happen that often.




回答3:


The question is also: how did they test the performance?

Writing good microbenchmarks is not easy.

Here are some good articles:

http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html

http://www.ibm.com/developerworks/java/library/j-benchmark2/index.html

http://ellipticgroup.com/html/benchmarkingArticle.html



来源:https://stackoverflow.com/questions/38922137/jdk8-performance-of-arraylist-compared-to-linkedlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!