簡體   English   中英

在集合集合中添加元素的最快方法

[英]The fastest way to add elements in set collection

我有一個任務是在樹集> 10000000元素序列中添加。

如果我使用

for (long index = 0; index < 10000000; index++)
    {
        result.add(index);
    }

它需要8083毫秒。 是否有任何解決方案可以提高此任務的性能?

https://github.com/cyberterror/TestRanges

PS目前最快的方法是: List<Integer> range = IntStream.range(0, 10000000).boxed().collect(Collectors.toList()); 結果約為370毫秒

您已經按正確的順序添加項目,TreeSet將在每個復雜的添加項目后自行排序,LinkedHashSet只保留插入順序。

所以,如果你真的需要一個Set來實現LinkedHashSet實現,就像這里:

Set<Long> result = new LinkedHashSet<Long>();
for (Long index = 0L; index != 10000000L;) { //Avoid autoboxing
    result.add(index++);
}

請閱讀: https//dzone.com/articles/hashset-vs-treeset-vs

你真的需要收藏嗎? 為了這個目的,如果是這樣的話? 實際上,使用普通陣列可以提高性能。

   long [] ar = new long[10000000];
    for (int i = 0; i < 10000000; i++) {
        ar[i] = (long )i;
    }

...

BUILD SUCCESS
------------------------------------------------------------------------
Total time: 0.553 s

UPD:實際上,可以使用Arrays實用程序對陣列執行大多數操作

long [] ar = new long[10000000];
for (int i = 0; i < 10000000; i++) {
    ar[i] = (long )i;
}

long[] copyOfRange = Arrays.copyOfRange(ar, 50000, 1000000);

...

BUILD SUCCESS
------------------------------------------------------------------------
Total time: 0.521 s

試用HPPC:Java的高性能原始集合

許可證:Apache License 2.0

<dependency>
  <groupId>com.carrotsearch</groupId>
  <artifactId>hppc</artifactId>
  <version>0.7.1</version>
</dependency>

LongHashSet在1190ms內執行:

LongSet result = new LongHashSet();
for (Long index = 0L; index < 10000000L;) {
  result.add(index++);
}

LongScatterSet在850ms內執行:

LongSet result = new LongScatterSet();
for (Long index = 0L; index < 10000000L;) {
  result.add(index++);
}

TreeSet是一種平衡的紅黑樹。 每次添加新項目時,樹都要平衡需要花費很多時間。 嘗試以不同的順序添加項目; 實際上按此順序:

  • 5 000 000 - 中間0和10 000 000(你的集合大小是10 000 000)
  • 2 500 000 - 中間0和5 000 000
  • 7 500 000 - 中間5 000 000和10 000 000
  • 數字在0和2 500 000中間
  • 數字在2 500 000和5 000 000之間
  • 數量在5 000 000和7 500 000之間
  • 數字在7 500 000和10 000 000之間
  • 等等

這樣,您將保持樹總是平衡,不會執行其他操作(以平衡樹)。 只需確保您的算法計算下一個要添加的數字並不太復雜。

暫無
暫無

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

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