简体   繁体   中英

Runtime of traversal over LinkedList vs ArrayList in Java

I'm getting strange results in a rather simple piece of code. Here is the code in question:

    List<Integer> arrayList = new ArrayList<Integer>(6200000);
    List<Integer> linkedList = new LinkedList<Integer>();

    for (int i = 0; i < 6200000; i++)
    {
        arrayList.add(i);
    }

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 6200000; i++)
    {
        linkedList.add(i);
    }
    System.out.println(System.currentTimeMillis() - startTime);

Now, here is the problem: When size is given as argument to ArrayList CTOR, as in "new ArrayList(6200000)" , the printed value is always greater than 2000. When size is not given to ArrayList CTOR, as in "new ArrayList()" , the printed value is 1000 or a bit over 1000. The thing is that multiple executions give different values, but my point is that there is a significant difference between the two described scenarios, and I just don't understand why. how the way the ArrayList is constructed affects the code related to the LinkedList? Does anyone have a clue?

Thanks!

When you add nodes to a LinkedList you are create a lot of objects (two per value) so you will be stressing the memory allocator. When you create a very large data structure like you are in the first instance you will be focusing the memory sizes to grow. In the case of new ArrayList() you are focusing to grow the most as the ArrayList has to resize many times, most like resulting in a larger Eden size speeding up short lived objects. I would watch what the heap sizes are doing while you run this test to see how the memory grows differently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM