Approach

We are going to use a list of 10.000.000 of elements, generated randomly, and we are going to calculate the average response time in 10 iterations.

As JMHdoesn’t allow sharing data between benchmarks, we are going to create a file with the list of elements, and read from it by each benchmark. In that way, we guarantee we are measuring the same scenario.

Deleting from the End – remove(size - 1)

Now, let’s see the code for measuring how ArrayList and LinkedList behave when we need to remove from the end:

That is pretty interesting, LinkedList and ArrayList have pretty much a equal behavior. Let’s see why they behave like that.

NOTE: Careful, if you run those tests multiple times, the result mightn’t be equal

ArrayList

Well, let’s use this example:

ArrayList example

Now, we want to remove the index 6 of the list. So, ArrayList will do the following:

Set NULL the 6 position:

Set null the last position

2. Change the array size variable from 7 to 6:

Reduce the size in one

TIP: In a logic point of view, the ArrayList size is now 6, however, its pure array is 7. That means, the next time we need to add a new element at the end, is going to be fast, there is a position available.

We can conclude:

In the worst case, we just need to set NULL the last position

The amount of operations is 1.

The complexity of this operation is O(1).

LinkedList

Well, let’s use this example:

LinkedList example

Now, we want to remove the 6 index from the list. This is the process:

1.Move the Tail one index before:

Move the Tail one index before

2. Unlink the previous Tail from the new Tail:

Unlink the new Tail from the old Tail

3. The garbage collector is going to reclaim the unlinked node:

Unlinked node disappear

We can conclude:

We only need to unlink the node from the Tail.

The amount of operations is 1.

The complexity of this operation is O(1).

Deleting from the Middle – remove(size / 2)

Now, let’s see the code for measuring how ArrayList and LinkedList behave when we need to remove from the middle:

Like this:

Related

Published by Daniel Andres Pelaez Lopez

I am Daniel Andres Pelaez Lopez. I am a Software Engineer with more than 10 years of experience developing software.
Doing software is easy, doing it well and in a professional way, is not.
I created this blog to share my experiences and thoughts about being a professional Software Engineer, I believe that with stronger concepts and bases, we can grow higher in our careers.
View all posts by Daniel Andres Pelaez Lopez