Skip to content

Instantly share code, notes, and snippets.

@dvbobrov
Last active January 1, 2016 17:49
Show Gist options
  • Save dvbobrov/8179931 to your computer and use it in GitHub Desktop.
Save dvbobrov/8179931 to your computer and use it in GitHub Desktop.
package com.dbobrov.benchmark;
import org.openjdk.jmh.annotations.*;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class JDK8HashSet {
private static class Simple {
private final int hc;
public Simple(int hc) {
this.hc = hc;
}
@Override
public int hashCode() {
return hc;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
private static class Ordered extends Simple implements Comparable<Ordered> {
private final int c;
public Ordered(int hc, int c) {
super(hc);
this.c = c;
}
@Override
public int compareTo(Ordered o) {
return Integer.compare(c, o.c);
}
}
@GenerateMicroBenchmark
public Set<Simple> measureSimple() {
Set<Simple> set = new HashSet<>();
for (int i = 0; i < 100; i++) {
set.add(new Simple(1));
}
return set;
}
@GenerateMicroBenchmark
public Set<Ordered> measureOrdered() {
Set<Ordered> set = new HashSet<>();
for (int i = 0; i < 100; i++) {
set.add(new Ordered(1, i));
}
return set;
}
@GenerateMicroBenchmark
public Set<Simple> measurePartiallyOrdered1() {
Set<Simple> set = new HashSet<>();
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
set.add(new Simple(1));
} else {
set.add(new Ordered(1, i));
}
}
return set;
}
@GenerateMicroBenchmark
public Set<Simple> measurePartiallyOrdered2() {
Set<Simple> set = new HashSet<>();
for (int i = 0; i < 100; i++) {
if (i % 4 == 0) {
set.add(new Simple(1));
} else {
set.add(new Ordered(1, i));
}
}
return set;
}
}
c.d.b.JDK8HashSet.measureOrdered avgt 1 10 1 21.373 1.085 us/op
c.d.b.JDK8HashSet.measurePartiallyOrdered1 avgt 1 10 1 100.075 0.586 us/op
c.d.b.JDK8HashSet.measurePartiallyOrdered2 avgt 1 10 1 72.480 0.221 us/op
c.d.b.JDK8HashSet.measureSimple avgt 1 10 1 112.671 0.755 us/op
@shipilev
Copy link

Would be even faster if you don't pay the upfront cost of System.iHC():

    private static class Ordered ... {
        private int id;

        public Ordered(int hc, int id) {
            ...
            this.id = id;
        }

        public int compareTo(Ordered o) {
            return Integer.compare(id, o.id);
        }
    }

    ...

    new Ordered(1, i);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment