|
| 1 | +package com.baeldung.performance; |
| 2 | + |
| 3 | +import org.openjdk.jmh.annotations.*; |
| 4 | +import org.openjdk.jmh.runner.Runner; |
| 5 | +import org.openjdk.jmh.runner.options.Options; |
| 6 | +import org.openjdk.jmh.runner.options.OptionsBuilder; |
| 7 | + |
| 8 | +import java.util.*; |
| 9 | +import java.util.concurrent.TimeUnit; |
| 10 | + |
| 11 | +@BenchmarkMode(Mode.AverageTime) |
| 12 | +@OutputTimeUnit(TimeUnit.MICROSECONDS) |
| 13 | +@Warmup(iterations = 10) |
| 14 | +public class HashMapBenchmark { |
| 15 | + |
| 16 | + @State(Scope.Thread) |
| 17 | + public static class MyState { |
| 18 | + |
| 19 | + Map<Long, Employee> employeeMap = new HashMap<>(); |
| 20 | + //LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>(); |
| 21 | + //IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>(); |
| 22 | + //WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>(); |
| 23 | + //ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>(); |
| 24 | + //ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>(); |
| 25 | + |
| 26 | + // TreeMap |
| 27 | + |
| 28 | + long iterations = 100000; |
| 29 | + |
| 30 | + Employee employee = new Employee(100L, "Harry"); |
| 31 | + |
| 32 | + int employeeIndex = -1; |
| 33 | + |
| 34 | + @Setup(Level.Trial) |
| 35 | + public void setUp() { |
| 36 | + for (long i = 0; i < iterations; i++) { |
| 37 | + employeeMap.put(i, new Employee(i, "John")); |
| 38 | + } |
| 39 | + |
| 40 | + //employeeMap.put(iterations, employee); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + @Benchmark |
| 45 | + public Employee testGet(HashMapBenchmark.MyState state) { |
| 46 | + return state.employeeMap.get(state.iterations); |
| 47 | + } |
| 48 | + |
| 49 | + @Benchmark |
| 50 | + public Employee testRemove(HashMapBenchmark.MyState state) { |
| 51 | + return state.employeeMap.remove(state.iterations); |
| 52 | + } |
| 53 | + |
| 54 | + @Benchmark |
| 55 | + public Employee testPut(HashMapBenchmark.MyState state) { |
| 56 | + return state.employeeMap.put(state.employee.getId(), state.employee); |
| 57 | + } |
| 58 | + |
| 59 | + @Benchmark |
| 60 | + public Boolean testContainsKey(HashMapBenchmark.MyState state) { |
| 61 | + return state.employeeMap.containsKey(state.employee.getId()); |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + public static void main(String[] args) throws Exception { |
| 66 | + Options options = new OptionsBuilder() |
| 67 | + .include(HashMapBenchmark.class.getSimpleName()).threads(1) |
| 68 | + .forks(1).shouldFailOnError(true) |
| 69 | + .shouldDoGC(true) |
| 70 | + .jvmArgs("-server").build(); |
| 71 | + new Runner(options).run(); |
| 72 | + } |
| 73 | +} |
0 commit comments