77 lines
1.9 KiB
Java
Raw Normal View History

2016-08-18 11:05:53 -06:00
// understandingcollections/jmh/Maps.java
2016-08-05 16:07:30 -06:00
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Performance differences between Maps
2016-08-18 11:05:53 -06:00
package understandingcollections.jmh;
2016-08-05 16:07:30 -06:00
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.*;
import static java.util.concurrent.TimeUnit.*;
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, timeUnit = SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = SECONDS)
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(MICROSECONDS)
2016-08-06 11:30:08 -06:00
public class Maps {
2016-08-05 16:07:30 -06:00
private Map<Integer, Integer> map;
2016-08-06 11:30:08 -06:00
@Param({"HashMap", "TreeMap", "LinkedHashMap",
"IdentityHashMap", "WeakHashMap", "Hashtable",})
2016-08-05 16:07:30 -06:00
private String type;
private int begin;
private int end;
@Setup
public void setup() {
switch(type) {
2016-08-06 11:30:08 -06:00
case "HashMap":
2016-08-05 16:07:30 -06:00
map = new HashMap<>();
break;
2016-08-06 11:30:08 -06:00
case "TreeMap":
2016-08-05 16:07:30 -06:00
map = new TreeMap<>();
break;
2016-08-06 11:30:08 -06:00
case "LinkedHashMap":
2016-08-05 16:07:30 -06:00
map = new LinkedHashMap<>();
break;
2016-08-06 11:30:08 -06:00
case "IdentityHashMap":
2016-08-05 16:07:30 -06:00
map = new IdentityHashMap<>();
break;
2016-08-06 11:30:08 -06:00
case "WeakHashMap":
2016-08-05 16:07:30 -06:00
map = new WeakHashMap<>();
break;
2016-08-06 11:30:08 -06:00
case "Hashtable":
2016-08-05 16:07:30 -06:00
map = new Hashtable<>();
break;
default:
throw new IllegalStateException("Unknown " + type);
}
begin = 1;
end = 256;
for (int i = begin; i < end; i++) {
map.put(i, i);
}
}
@Benchmark
public void get(Blackhole bh) {
for (int i = begin; i < end; i++) {
bh.consume(map.get(i));
}
}
@Benchmark
2016-08-06 11:30:08 -06:00
public void put() {
2016-08-05 16:07:30 -06:00
for (int i = begin; i < end; i++) {
2016-08-06 11:30:08 -06:00
map.put(i, i);
2016-08-05 16:07:30 -06:00
}
}
@Benchmark
public void iterate(Blackhole bh) {
Iterator it = map.entrySet().iterator();
while(it.hasNext())
bh.consume(it.next());
}
}