簡體   English   中英

為什么初始容量對於從 ArrayList 中刪除很重要?

[英]Why is initial capacity important for deleting from ArrayList?

對於我的工作,我對時間圖做了一些測試。 我遇到了一些讓我感到驚訝的事情,需要幫助理解它。

我使用了很少的數據結構作為隊列,並想知道根據項目數量刪除的速度如何。 而arraylist有10個項目,從前面刪除並且沒有設置初始容量比設置初始容量(到15)慢得多。 為什么? 以及為什么它在 100 個項目中相同。

這是圖表: 在此處輸入圖片說明

數據結構:L - 實現列表,C - 設置初始容量,B - 從后面移除,Q - 實現隊列

編輯:附加相關的一段代碼

new Thread(new Runnable() {
 @Override
 public void run()
 {
  long time;
  final int[] arr = {10, 100, 1000, 10000, 100000, 1000000};
  for (int anArr : arr)
  {
    final List<Word> temp = new ArrayList<>();
    while (temp.size() < anArr) temp.add(new Item());

    final int top = (int) Math.sqrt(anArr);

    final List<Word> first = new ArrayList<>();
    final List<Word> second = new ArrayList<>(anArr);
    ...
    first.addAll(temp);
    second.addAll(temp);
    ...

    SystemClock.sleep(5000);

    time = System.nanoTime();
    for (int i = 0; i < top; ++i) first.remove(0);
    Log.d("al_l", "rem: " + (System.nanoTime() - time));

    time = System.nanoTime();
    for (int i = 0; i < top; ++i) second.remove(0);
    Log.d("al_lc", "rem: " + (System.nanoTime() - time));

    ...
   }
  }
}).start();

閱讀這篇關於避免 JVM 上的基准測試陷阱的文章。 它解釋了 Hotspot VM 對測試結果的影響。 如果你不注意它,你的測量是不正確的。 正如您在自己的測試中發現的那樣。

如果您想進行可靠的基准測試,請使用JMH

我也能夠通過創建下面的代碼來復制它。 但是,我注意到首先運行的內容(設置容量與非設置容量)是最耗時的。 我認為這是某種優化,也許是 JVM,或者某種緩存?

public class Test {



public static void main(String[] args) {
        measure(-1, 10); // switch with line below
        measure(15, 10); // switch with line above
        measure(-1, 100);
        measure(15, 100);
    }

    public static void measure(int capacity, long numItems) {
        ArrayList<String> arr = new ArrayList<>();

        if (capacity >= 1) {
            arr.ensureCapacity(capacity);
        }

        for (int i = 0; i <= numItems; i++) {
            arr.add("T");
        }
        long start = System.nanoTime();

        for (int i = 0; i <= numItems; i++) {
            arr.remove(0);
        }

        long end = System.nanoTime();
        System.out.println("Capacity: " + capacity + ", " + "Runtime: "
                + (end - start));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM