不可变集合相比可变集合_简单的基准测试:不可变集合VS持久集合
生活随笔
收集整理的這篇文章主要介紹了
不可变集合相比可变集合_简单的基准测试:不可变集合VS持久集合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不可變集合相比可變集合
通常,您需要向集合中添加新元素。
因為您是一個優秀而謹慎的開發人員,所以您希望盡可能保持不變。 因此,向不可變集合中添加新元素將意味著您必須創建一個新的不可變集合,其中包含原始集合的所有元素以及新元素。
您可以使用guava庫以及最近的pCollection庫來創建不可變的集合。
在下面的示例中,我們將構建2個不可變列表,其中一個來自guava不可變,另一個來自pCollection持久。
它們最初都將包含10.000整數。
我們將為每種類型創建20.000個不可變列表,我們將測量花費的時間。
package com.marco.pcollections;import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import org.pcollections.PCollection; import org.pcollections.TreePVector;import com.google.common.collect.ImmutableList;public class PcollectionVSImmutable {public static void main(String[] args) {Map<Integer, ImmutableList<Object>> allImmutable = new HashMap<Integer, ImmutableList<Object>>();Map<Integer, PCollection<Integer>> allPersistent = new HashMap<Integer, PCollection<Integer>>();List<Integer> bigList = new ArrayList<Integer>();for (int i = 0; i < 10000; i++) {bigList.add(new Integer(i));}ImmutableList<Integer> immutable = ImmutableList.copyOf(bigList);PCollection<Integer> persistent = TreePVector.from(bigList);long start = System.currentTimeMillis();for (int i = 10000; i < 30000; i++) {allPersistent.put(new Integer(i), persistent.plus(new Integer(i)));}System.out.println("creating 20.000 pCollections takes : " + (System.currentTimeMillis() - start) + "ms");start = System.currentTimeMillis();for (int i = 10000; i < 30000; i++) {allImmutable.put(new Integer(i), ImmutableList.builder().addAll(immutable).add(new Integer(i)).build());}System.out.println("creating 20.000 Guava ImmutableList takes : " + (System.currentTimeMillis() - start) + "ms");System.out.println("All immutable size : " + allImmutable.size() + " allPersistent size : " + allPersistent.size());} }輸出:
creating 20.000 pCollections takes : 29ms creating 20.000 Guava ImmutableList takes : 18347ms All immutable size : 20000 allPersistent size : 20000翻譯自: https://www.javacodegeeks.com/2015/05/simple-benchmarking-immutable-collections-vs-persistent-collections.html
不可變集合相比可變集合
總結
以上是生活随笔為你收集整理的不可变集合相比可变集合_简单的基准测试:不可变集合VS持久集合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样发微信朋友圈文字
- 下一篇: jug java_架构大型企业Java项