Core Java

Simple benchmarking : Immutable Collections VS Persistent Collections

Often you need to add new elements to a collection.

Because you are a good and careful developer you want to keep things immutable as much as possible. So adding a new element to an immutable collections will mean that you have to create a new immutable collection that contains all the elements of the original collections plus the new element.

You can create immutable collections using the guava library and also using the recent pCollection library.

In the following example, we will build 2 immutable lists, one immutable from guava and one persistent from pCollection.

They both will contain 10.000 integers initially.

We will create 20.000 immutable lists one for each type and we will measure the time taken.

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());

        }
}

Output :

creating 20.000 pCollections takes : 29ms
creating 20.000 Guava ImmutableList takes : 18347ms
All immutable size : 20000 allPersistent size : 20000
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button