Pages

Friday, March 25, 2011

Load factor for HashSet with contains operation

Update: This post really contains zero valuable information and is left here merely as a memorial to my stupidity.

In previous post I have measured the performance of HashSet with various load factors and initial capacity on the add operation. But the often case is that the most common operation on the set is checking whether an element contains in the set. So without much comments - another silly bench:


private static final int MAX_ITERATIONS = 100000;

  public static void main(String[] args) {
    Set<String> setWithLoad1 = new HashSet<String>(MAX_ITERATIONS, 1f);
    Set<String> setWithExactSize = new HashSet<String>(MAX_ITERATIONS);
    Set<String> setWithBiggerSize = new HashSet<String>(Math.round(MAX_ITERATIONS * 1.4f));

    for (int i = 0; i < MAX_ITERATIONS; i++) {
      setWithLoad1.add("String number ".concat(String.valueOf(i)));
      setWithExactSize.add("String number ".concat(String.valueOf(i)));
      setWithBiggerSize.add("String number ".concat(String.valueOf(i)));
    }

    long loadFactorOneTime = 0, exactSizeTime = 0, biggerSizeTime = 0;
    for (int i = 0; i < 1000; i++) {
      long nanoTime;

      nanoTime = System.nanoTime();
      doWithSet(setWithBiggerSize);
      biggerSizeTime += System.nanoTime() - nanoTime;

      nanoTime = System.nanoTime();
      doWithSet(setWithExactSize);
      exactSizeTime += System.nanoTime() - nanoTime;

      nanoTime = System.nanoTime();
      doWithSet(setWithLoad1);
      loadFactorOneTime += System.nanoTime() - nanoTime;
    }

    System.out.println("With load factor 1 : " + loadFactorOneTime);
    System.out.println("With exact size  : " + exactSizeTime);
    System.out.println("With bigger size  : " + biggerSizeTime);

  }

  private static void doWithSet(Set<String> set) {
    for (int i = 0; i < MAX_ITERATIONS; i++) {
      set.contains("String number ".concat(String.valueOf(i)));
      set.contains("String number ".concat(String.valueOf(MAX_ITERATIONS * 2 - i)));
    }
  }

Output:
With load factor 1 : 36785852695
With exact size    : 34131217564
With bigger size   : 33591675784

I really don't see how and when should the load factor be used...

No comments:

Post a Comment