0

I have been thinking that LinkedList fills faster than ArrayList. As I know ArrayList is based on simple array with limited length(constant). So every time array is out of range, new array with higher range will be created. LinkedList is much simpler. It hasn't got any limit (except for memory), so it should be filled faster. But I run next code:

 public static void main(String[] args) {
 int length = 7000000;
 List<Integer> list = new LinkedList<Integer>();
 long oldTime = System.currentTimeMillis();
 for (int i = 0; i < length; i++) {
 list.add(i);
 }
 System.out.println("LinkedList fill: " + (System.currentTimeMillis() - oldTime));
 list = new ArrayList<Integer>();
 oldTime = System.currentTimeMillis();
 for (int i = 0; i < length; i++) {
 list.add(i);
 }
 System.out.println("ArrayList fill: " + (System.currentTimeMillis() - oldTime));
 }

The output is:

LinkedList fill: 3936
ArrayList fill: 628

Why so?

asked Oct 16, 2014 at 12:19
4
  • 4
    Because your benchmark is flawed. stackoverflow.com/questions/504103/… Commented Oct 16, 2014 at 12:20
  • Did you try to swap them? First the arraylist and than the linkedlist? Commented Oct 16, 2014 at 12:21
  • if you do vice versa i.e. ArrayList first and then LL? Also pass on the length to ArrayList constructor and see what happens? Commented Oct 16, 2014 at 12:22
  • Nothing changes. You could run them separately in two different programms. Commented Oct 16, 2014 at 12:23

1 Answer 1

2

You can't really benchmark performance like that in Java. See How do I write a correct micro-benchmark in Java? for a more detailed explanations of the many things that can go wrong.

If I test your code with jmh I get the following results:

Benchmark Mode Samples Score Error Units
c.a.p.SO26404256.arrayList avgt 5 7.661 ± 0.672 ms/op
c.a.p.SO26404256.linkedList avgt 5 9.675 ± 1.213 ms/op

So filling a LinkedList seems to be slightly slower than filling an arrayList, but the difference is a lot less than your test indicated.

As for the reason for the difference, it is probably because each element of a LinkedList is wrapped in a Node: that means more object creations and more garbage collections. And the penalty due to array copies in ArrayList is probably less than you think because they are highly optimised.

answered Oct 16, 2014 at 12:31
1
  • All in one link by Oracle Wiki. See Relevant links too.. Commented Oct 16, 2014 at 12:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.