2016-12-29 21:24:00 -08:00
|
|
|
// moreaboutcollections/jmh/Maps.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2016-08-05 16:07:30 -06:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-08-05 16:07:30 -06:00
|
|
|
// 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.*;
|
2016-10-22 13:35:19 -07:00
|
|
|
import java.util.concurrent.*;
|
2016-08-05 16:07:30 -06:00
|
|
|
|
|
|
|
@State(Scope.Thread)
|
2016-10-22 13:35:19 -07:00
|
|
|
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
|
|
|
@Warmup(iterations = 5, batchSize = 5000)
|
|
|
|
@Measurement(iterations = 5, batchSize = 5000)
|
|
|
|
@BenchmarkMode(Mode.SingleShotTime)
|
2016-08-05 16:07:30 -06:00
|
|
|
@Fork(1)
|
2016-08-06 11:30:08 -06:00
|
|
|
public class Maps {
|
2016-10-22 13:35:19 -07:00
|
|
|
private Map<String,String> map;
|
2016-08-05 16:07:30 -06:00
|
|
|
|
2016-10-22 13:35:19 -07:00
|
|
|
@Param({
|
|
|
|
"java.util.HashMap",
|
|
|
|
"java.util.Hashtable",
|
|
|
|
"java.util.TreeMap",
|
|
|
|
"java.util.LinkedHashMap",
|
|
|
|
"java.util.IdentityHashMap",
|
|
|
|
"java.util.WeakHashMap",
|
|
|
|
"java.util.concurrent.ConcurrentHashMap",
|
|
|
|
"java.util.concurrent.ConcurrentSkipListMap",
|
|
|
|
})
|
2016-08-05 16:07:30 -06:00
|
|
|
private String type;
|
|
|
|
|
2016-10-22 13:35:19 -07:00
|
|
|
@Param({
|
|
|
|
"1",
|
|
|
|
"10",
|
|
|
|
"100",
|
|
|
|
"1000",
|
|
|
|
"10000",
|
|
|
|
})
|
|
|
|
private int size;
|
2016-08-05 16:07:30 -06:00
|
|
|
|
2016-11-01 11:43:22 -07:00
|
|
|
private String key;
|
|
|
|
|
2016-08-05 16:07:30 -06:00
|
|
|
@Setup
|
2016-11-21 12:37:57 -08:00
|
|
|
@SuppressWarnings("unchecked")
|
2016-11-01 11:43:22 -07:00
|
|
|
public void setup() throws Exception {
|
|
|
|
map = (Map<String,String>)
|
|
|
|
Class.forName(type).newInstance();
|
2016-10-22 13:35:19 -07:00
|
|
|
for(int i = 0; i < size; i++)
|
|
|
|
map.put(Integer.toString(i), Integer.toString(i));
|
2016-11-01 11:43:22 -07:00
|
|
|
key = Integer.toString(size / 2);
|
|
|
|
}
|
|
|
|
@Benchmark
|
|
|
|
public boolean containsKey() {
|
|
|
|
return map.containsKey(key);
|
2016-08-05 16:07:30 -06:00
|
|
|
}
|
|
|
|
@Benchmark
|
2016-11-01 11:43:22 -07:00
|
|
|
public String get() {
|
|
|
|
return map.get(key);
|
2016-08-05 16:07:30 -06:00
|
|
|
}
|
|
|
|
@Benchmark
|
2016-10-22 13:35:19 -07:00
|
|
|
public Map<String,String> put() {
|
|
|
|
map.put("test", "test");
|
|
|
|
return map;
|
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());
|
|
|
|
}
|
|
|
|
}
|