Skip to content

Commit 71a6aa7

Browse files
author
Bruce Eckel
committed
Initial Reasonable JMH example working
1 parent b72a223 commit 71a6aa7

2 files changed

Lines changed: 81 additions & 66 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// understandingcollections/jmhtests/MapPerformance.java
2+
// (c)2016 MindView LLC: see Copyright.txt
3+
// We make no guarantees that this code is fit for any purpose.
4+
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
5+
// Performance differences between Maps
6+
package understandingcollections.jmhtests;
7+
import org.openjdk.jmh.annotations.*;
8+
import org.openjdk.jmh.infra.Blackhole;
9+
import java.util.*;
10+
import static java.util.concurrent.TimeUnit.*;
11+
12+
@State(Scope.Thread)
13+
@Warmup(iterations = 5, time = 1, timeUnit = SECONDS)
14+
@Measurement(iterations = 5, time = 1, timeUnit = SECONDS)
15+
@Fork(1)
16+
@BenchmarkMode(Mode.AverageTime)
17+
@OutputTimeUnit(NANOSECONDS)
18+
public class MapPerformance {
19+
private Map<Integer, Integer> map;
20+
21+
@Param({"hashmap", "treemap", "linkedhashmap",
22+
"identityhashmap", "weakhashmap", "hashtable"})
23+
private String type;
24+
25+
private int begin;
26+
private int end;
27+
28+
@Setup
29+
public void setup() {
30+
switch(type) {
31+
case "hashmap":
32+
map = new HashMap<>();
33+
break;
34+
case "treemap":
35+
map = new TreeMap<>();
36+
break;
37+
case "linkedhashmap":
38+
map = new LinkedHashMap<>();
39+
break;
40+
case "identityhashmap":
41+
map = new IdentityHashMap<>();
42+
break;
43+
case "weakhashmap":
44+
map = new WeakHashMap<>();
45+
break;
46+
case "hashtable":
47+
map = new Hashtable<>();
48+
break;
49+
default:
50+
throw new IllegalStateException("Unknown " + type);
51+
}
52+
53+
begin = 1;
54+
end = 256;
55+
for (int i = begin; i < end; i++) {
56+
map.put(i, i);
57+
}
58+
}
59+
60+
@Benchmark
61+
public void get(Blackhole bh) {
62+
for (int i = begin; i < end; i++) {
63+
bh.consume(map.get(i));
64+
}
65+
}
66+
67+
@Benchmark
68+
public void put(Blackhole bh) {
69+
for (int i = begin; i < end; i++) {
70+
bh.consume(map.put(i, i));
71+
}
72+
}
73+
74+
@Benchmark
75+
public void iterate(Blackhole bh) {
76+
Iterator it = map.entrySet().iterator();
77+
while(it.hasNext())
78+
bh.consume(it.next());
79+
}
80+
81+
}

understandingcollections/jmhtests/MapPerformanceJMH.java

Lines changed: 0 additions & 66 deletions
This file was deleted.

0 commit comments

Comments
 (0)