HashSet Vs LinkedHashSet Performance Test

From here I red that HashSet has slightly better performance than LinkedHashSet. But when tried to execute a sample program, I getting a different result.

     /*
     * HashSet not order not sorted
     */
    long hsTime = System.nanoTime();
    Set<String> hs = new HashSet<String>();
      // add elements to the hash set
    hs.add("B");
    hs.add("A");
    hs.add("D");
    hs.add("E");
    hs.add("C");
    hs.add("F");
    System.out.println("HashSet ---->"+hs); // HashSet ---->[D, E, F, A, B, C]
    System.out.println("Execution time HashSet ---->"+(System.nanoTime() - hsTime)); // Execution time HashSet ---->275764

    /*
     * LinkedHashSet will maintain its insertion order but no sorting
     */
    long lhsTime  = System.nanoTime();
    Set<String> lhs = new LinkedHashSet<String>();
      // add elements to the hash set
    lhs.add("B");
    lhs.add("A");
    lhs.add("D");
    lhs.add("E");
    lhs.add("C");
    lhs.add("F");
    System.out.println("LinkedHashSet ---->"+lhs); //LinkedHashSet ---->[B, A, D, E, C, F]
    System.out.println("Execution time LinkedHashESet ---->"+(System.nanoTime() - lhsTime)); // Execution time LinkedHashESet ---->201181

Showing that LinkedHashSet having better performance. Can someone clarify which one having better performance.

Note: When I comment out these two lines :

System.out.println("HashSet ---->"+hs);
System.out.println("LinkedHashSet ---->"+lhs);

It is showing HashSet having better performance. Where the output is

Execution time HashSet ---->32304
Execution time LinkedHashESet ---->74414

Upvotes: 1

Views: 1537

Answers (1)

M A
M A

Reputation: 72844

I suspect it is due to the warmup time taken by the JVM when doing the first loop when outputing the HashSet in the following statement:

System.out.println("HashSet ---->"+hs);

which is equivalent to something like

Iterator<E> i = iterator();
if (! i.hasNext())
    return "[]";

StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
    E e = i.next();
    sb.append(e == this ? "(this Collection)" : e);
    if (! i.hasNext())
    return sb.append(']').toString();
    sb.append(", ");
}
System.out.println("HashSet ---->" + sb.toString());

Upvotes: 1

Related Questions