When you add to an ArrayList
, you just have to store the integer in the backing array. Every once in a while, when the backing array fills up, you have to allocate a new array and copy all the old items to the new array. Given 5 million integers, you'll have to do that allocate-and-copy about 20 times (depends on the initial size of the list).
To add to a linked list, every addition requires that you:
- Allocate memory for and initialize a new linked list node.
- Link the new node to the end of the list.
All that extra work, for both the ArrayList
and the LinkedList
is done behind the scenes, by the add
method.
The overhead for 5 million linked list node allocations and links is higher than the overhead for 5 million ArrayList
insertions, even when you count the 20 or so allocate-and-copy operations that the ArrayList
has to make when it fills up.
So, whereas each operation takes constant time (although in the ArrayList
case it's really amortized constant time), the constant for appending to a linked list is higher than the constant for appending to an ArrayList
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…