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
5
  • Ye and now try to add something inside list insteed of appending new element. Also did you perform dry run before that? Commented Apr 18, 2018 at 4:48
  • I remember reading somewhere that in practice, ArrayList almost always outperforms LinkedList, even where you'd expect it to be slower. Commented Apr 18, 2018 at 4:56
  • @AndyTurner How is that a duplicate? Commented Apr 18, 2018 at 4: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 Commented Apr 18, 2018 at 5: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 Commented Apr 18, 2018 at 5:56

1 Answer 1

-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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.