What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed.
I know that the Big O notation for get is O(1) and add is O(1) for an ArrayList, while LinkedList is O(n) for get and O(1) for add. Does the iterator behave with the same Big O notation?
What is the fastest list implementation (in java) in a scenario where the list
Share
It depends largely on whether you know the maximum size of each list up front.
If you do, use
ArrayList; it will certainly be faster.Otherwise, you’ll probably have to profile. While access to the
ArrayListis O(1), creating it is not as simple, because of dynamic resizing.Another point to consider is that the space-time trade-off is not clear cut. Each Java object has quite a bit of overhead. While an
ArrayListmay waste some space on surplus slots, each slot is only 4 bytes (or 8 on a 64-bit JVM). Each element of aLinkedListis probably about 50 bytes (perhaps 100 in a 64-bit JVM). So you have to have quite a few wasted slots in anArrayListbefore aLinkedListactually wins its presumed space advantage. Locality of reference is also a factor, andArrayListis preferable there too.In practice, I almost always use
ArrayList.