1

I've observed that the insertion operation in ArrayList takes less time (in milliseconds) compared to LinkedList. Please shed some light on this.

Here's my test code:

List<String> strLnkdList = new LinkedList<String>();

long start1 = System.currentTimeMillis();
for(int i=0;i<10000;i++){
    strLnkdList.add("Test"+i);
}
long end1 = System.currentTimeMillis();
System.out.println("LinkedList Time in millis: " + (end1-start1));

List<String> strArrayList = new ArrayList<String>(10);

start1 = System.currentTimeMillis();
for(int i=0;i<10000;i++){
    strArrayList.add("Test"+i);
}

end1 = System.currentTimeMillis();
System.out.println("ArrayList Time in millis: " + (end1-start1));

Output:

LinkedList Time in millis: 22
ArrayList Time in millis: 10
Azeem
  • 11,148
  • 4
  • 27
  • 40
Nitin Vnk
  • 11
  • 3
  • Ye and now try to add something inside list insteed of appending new element. Also did you perform dry run before that? – Antoniossss Apr 18 '18 at 04:48
  • I remember reading somewhere that in practice, ArrayList almost always outperforms LinkedList, even where you'd expect it to be slower. – shmosel Apr 18 '18 at 04:56
  • @AndyTurner How is that a duplicate? – shmosel Apr 18 '18 at 04:56
  • @Antoniossss as u suggested i tried with capacity of 10000 and output is still same i.e. LinkedList Time in millis: 37 ArrayList Time in millis: 16 – Nitin Vnk Apr 18 '18 at 05:03
  • @Antoniossss Now i tried to append or insert more in both.. this time "LinkedList" won :) i.e. ArrayList_2 Time in millis: 34 .... LinkedList_2 Time in millis: 4 ... Thanks – Nitin Vnk Apr 18 '18 at 05:56

1 Answers1

-1

The Linked List only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed.

The ArrayList all the elements need to be shifted to fill out the space created by removed element.

Some imagine a jenga tower for the array to make it 1 block shorter you have to pull it out then shift each block down 1

for the linked list its like if you had a string holding a block and you just cut it

Brendan
  • 119
  • 11