简体   繁体   English

Java 中遍历 LinkedList 与 ArrayList 的运行时

[英]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.现在,问题来了:当 size 作为参数提供给 ArrayList CTOR 时,如"new ArrayList(6200000)" ,打印值总是大于 2000。当未将 size 指定给 ArrayList CTOR 时,如"new ArrayList ()" ,打印的值是 1000 或 1000 多一点。问题是多次执行给出了不同的值,但我的观点是所描述的两种场景之间存在显着差异,我只是不明白为什么。 how the way the ArrayList is constructed affects the code related to the LinkedList? ArrayList 的构造方式如何影响与 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.当您将节点添加到 LinkedList 时,您将创建大量对象(每个值两个),因此您将给内存分配器带来压力。 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.new ArrayList()的情况下,您专注于增长最多,因为 ArrayList 必须多次调整大小,最像导致更大的 Eden 大小加速短寿命对象。 I would watch what the heap sizes are doing while you run this test to see how the memory grows differently.在您运行此测试时,我会观察堆大小的变化,以了解内存的增长方式有何不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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