001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.utils.collection;
015
016import java.util.HashSet;
017import java.util.Iterator;
018import java.util.Set;
019
020public class HashSetPerformance {
021
022  private static final int TIMES = 100000;
023  private static final int MAX = 500000;
024
025  public static void main(String[] argv) {
026    // first, get the JIT going
027    test(false, new CompactHashSet());
028    test(false, new HashSet());
029
030    // then, do real timings
031    System.out.println("*** HashSet ***");
032    for (int ix = 0; ix < 3; ix++) {
033      test(true, new HashSet());
034    }
035    System.out.println("*** CompactHashSet ***");
036    for (int ix = 0; ix < 3; ix++) {
037      test(true, new CompactHashSet());
038    }
039  }
040
041  public static void test(boolean output, Set set) {
042    long start = System.currentTimeMillis();
043
044    if (output) {
045      System.gc();
046      System.gc();
047    }
048    long before = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
049
050    // add
051    for (int ix = 0; ix < TIMES; ix++) {
052      set.add(new Long(Math.round(Math.random() * MAX)));
053    }
054
055    if (output) {
056      System.gc();
057      System.gc();
058      long after = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
059      System.out.println("Memory before: " + before);
060      System.out.println("Memory after: " + after);
061      System.out.println("Memory usage: " + (after - before));
062    }
063
064    // lookup
065    int count = 0;
066    for (int ix = 0; ix < TIMES; ix++) {
067      Long number = new Long(Math.round(Math.random() * MAX));
068      if (set.contains(number)) {
069        count++;
070      }
071    }
072
073    // iterate
074    Iterator it = set.iterator();
075    while (it.hasNext()) {
076      Long number = (Long) it.next();
077    }
078
079    // remove
080    for (int ix = 0; ix < TIMES; ix++) {
081      Long number = new Long(Math.round(Math.random() * MAX));
082      set.remove(number);
083    }
084
085    if (output) {
086      System.out.println("TIME: " + (System.currentTimeMillis() - start));
087    }
088  }
089}