Performance: ArrayList vs Linked List
Published in
6 min readMay 9, 2024
In this article let’s explore these two Java List structures and compare their performance in the following scenarios:
- Adding elements to the end of the list.
- Adding elements to the beginning of the list.
- Getting elements by index.
- Using the contains method to check if an element exists.
- Binary Search.
- Removing the Middle Element.
- Removing the First Element.
1. Adding Elements to the End of the List
Let’s start with the simplest scenario, which is adding elements to the end of the list. Below is the result of the performance test:
Key takeaways:
- Adding a few elements takes almost zero milliseconds for both lists.
- When adding a large number of elements (over 100k), ArrayList demonstrates better performance.
The performance difference is related to memory allocation. For each element added to the LinkedList, a new Node is created, resulting in a new memory allocation. This overhead is negligible when the number of elements is small.