In this tutorial, we will compare who is more faster-LinkedList or ArrayList.
As we have been listening the statement- ArrayList is
faster than LinkedList, except when you remove an element from the middle of the
list. Now in this tutorial we will perform test to verify how much extent
this statement is true.
In the given below example, We have created three function which first adds the element and then removes the element from the passed collection which is either LinkedList or ArrayList. The time is recorded before adding removing elements, so that it can give you a clear view of time taken by these two. The function getClass() returns the runtime class of an object. The method getSimpleName() returns the simple name of the underlying class as given in the source code.
Given below the code with its output :
package simpleCoreJava;
import java.util.*;
public class ListTest {
private static final int NUM_ELEMENTS = 100 * 1000;
public static void main(String[] args) {
List ar = new ArrayList();
for (int i = 0; i < NUM_ELEMENTS; i++) {
ar.add(i);
}
testListBeginning(ar);
testListBeginning(new LinkedList(ar));
testListMiddle(ar);
testListMiddle(new LinkedList(ar));
testListEnd(ar);
testListEnd(new LinkedList(ar));
}
public static void testListBeginning(List list) {
long time = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
list.add(0, new Object());
list.remove(0);
}
time = System.currentTimeMillis() - time;
System.out.println("beginning " + list.getClass().getSimpleName()
+ " took " + time);
}
public static void testListMiddle(List list) {
long time = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
list.add(NUM_ELEMENTS / 2, new Object());
list.remove(NUM_ELEMENTS / 2);
}
time = System.currentTimeMillis() - time;
System.out.println("middle " + list.getClass().getSimpleName()
+ " took " + time);
}
public static void testListEnd(List list) {
long time = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
list.add(new Object());
list.remove(NUM_ELEMENTS);
}
time = System.currentTimeMillis() - time;
System.out.println("end " + list.getClass().getSimpleName()
+ " took " + time);
}
}
beginning ArrayList took 3500 beginning LinkedList took 15 middle ArrayList took 1735 middle LinkedList took 20750 end ArrayList took 797 end LinkedList took 1578 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Which is Faster - LinkedList or ArrayList?
Post your Comment