Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EnumTest benchmark
/* EnumSet benchmark
* $ javac Benchmark.java
* $ java -ea Benchmark
* Ref: https://nullprogram.com/blog/2021/04/23/
*/
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
public final class Benchmark {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
benchmarkHashSet();
benchmarkEnumSet();
benchmarkBitflags();
}
}
static enum Flag { A, B, C, D, E, F, G }
static void benchmarkEnumSet() {
System.gc();
var beg = System.nanoTime();
Set<Flag> a = EnumSet.of(Flag.A, Flag.B, Flag.G);
for (int i = 0; i < 1_000_000_000; i++) {
Set<Flag> b = EnumSet.of(Flag.A, Flag.B, Flag.G);
assert a.equals(b);
}
var end = System.nanoTime();
System.out.println("EnumSet \t" + (end - beg)/1e9);
}
static void benchmarkHashSet() {
System.gc();
var beg = System.nanoTime();
Set<Flag> a = new HashSet<>(Arrays.asList(Flag.A, Flag.B, Flag.G));
for (int i = 0; i < 1_000_000_000; i++) {
Set<Flag> b = new HashSet<>(Arrays.asList(Flag.A, Flag.B, Flag.G));
assert a.equals(b);
}
var end = System.nanoTime();
System.out.println("HashSet \t" + (end - beg)/1e9);
}
static final int A = 1 << 0;
static final int B = 1 << 1;
static final int C = 1 << 2;
static final int D = 1 << 3;
static final int E = 1 << 4;
static final int F = 1 << 5;
static final int G = 1 << 6;
static void benchmarkBitflags() {
System.gc();
var beg = System.nanoTime();
var a = A | B | G;
for (int i = 0; i < 1_000_000_000; i++) {
var b = A | B | G;
assert a == b;
}
var end = System.nanoTime();
System.out.println("bitfield\t" + (end - beg)/1e9);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment