After reading this [question]: When to use LinkedList over ArrayList? I tried to benchmark the performance of ArrayList and LinkedList. But the result I found out is very different from the answer. ArrayList performance is 2-3 time better than LinkedList as far as add() is concerned. As far I know LinkedList.add(E element) is O(1) <--- main benefit of LinkedList ArrayList.add(E element) is O(n - index) But the result show that Array list is much faster than LinkedList
Can anyone please explain this behaviour
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Integer> b = new LinkedList<Integer>();
for (int i = 0; i < 1000000; i++) {
b.add(i);
}
System.out.println(System.currentTimeMillis() - start);
start = System.currentTimeMillis();
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < 1000000; i++) {
a.add(i);
}
System.out.println(System.currentTimeMillis() - start);
}