Why is LinkedHashSet Iteration faster than HashSet iteration in Java?

1.1k views Asked by At

Here is a sample code:

    Set<Integer> hashSet = new HashSet<>();
    Set<Integer> linkedHashSet = new HashSet<>();

    for(int i = 0; i < 1000; i++){
        hashSet.add(i);
        linkedHashSet.add(i);
    }

    Long startTimeHashSet = System.nanoTime();
    for(Integer i: hashSet){

    }
    Long endTimeHashSet = System.nanoTime();
    System.out.println("HashSet Time:" + (endTimeHashSet - startTimeHashSet));

    Long startTimeLinkedHashSet = System.nanoTime();
    for(Integer i: linkedHashSet){

    }
    Long endTimeLinkedHashSet = System.nanoTime();
    System.out.println("Linked HashSet Time:" + (endTimeLinkedHashSet - startTimeLinkedHashSet));

The output is:

HashSet Time:721774
Linked HashSet Time:132613

Why does this happen?

0

There are 0 answers