So I've stumbled across this bit of code and was wondering specifically why it is that the java.util.ArrayList
is significantly faster than the java.util.LinkedList
.
What the code does is create both an array and linked list and providing each a single element to start out with. The addMoreItems(List<Integer> vals)
will then run for both arrays, and for each it will insert a random value at some random index in the array. The amount of values that it will add to each array is determined by the input from the user.
private static int amount = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter amount of elements to add: ");
amount = scan.nextInt();
LinkedList<Integer> linked = new LinkedList<Integer>();
ArrayList<Integer> array = new ArrayList<Integer>();
linked.add(0);
array.add(0);
// Bench mark linked list speed
long start = System.nanoTime();
addMoreItems(linked);
long end = System.nanoTime() - start;
// Bench mark array list speed
long start2 = System.nanoTime();
addMoreItems(array);
long end2 = System.nanoTime() - start2;
System.out.println("Linked list took: " + (end / 1000000.0) + "ms");
System.out.println("Array list took: " + (end2 / 1000000.0) + "ms");
}
public static void addMoreItems(List<Integer> vals) {
Random r = new Random();
for (int i = 0; i < amount; i++)
vals.add(r.nextInt(vals.size()), r.nextInt());
}
So fundamentally, one would think that the addMoreItems()
function would take the same amount of time to return for both list types (maybe the LinkedList
would be slightly faster). However, the actual result seems to indicate that the ArrayList
is significantly faster than the linked list regardless of the number of elements you're adding (you can try it out here).
Anyways, my guess is that it may have to do with caching and maybe the fact that the LinkedList
will allocate memory for each individual element that is inserted, whereas the ArrayList
will allocate blocks of memory to reduce the number of allocations.
Why is the ArrayList
faster?