Skip to content

Instantly share code, notes, and snippets.

@apangin
Created July 29, 2021 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apangin/3c48f128c503bc8d25e27b66f78458a7 to your computer and use it in GitHub Desktop.
Save apangin/3c48f128c503bc8d25e27b66f78458a7 to your computer and use it in GitHub Desktop.
ConcurrentHashMap vs. HashMap performance
Benchmark (size) Mode Cnt Score Error Units
MapBench.chmGet 1024 avgt 5 20,363 ± 0,976 ns/op
MapBench.hmGet 1024 avgt 5 20,661 ± 0,898 ns/op
package bench;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
@State(Scope.Benchmark)
public class MapBench {
@Param({"1024"})
private int size;
private String[] keys;
private final Map<String, String> chm = new ConcurrentHashMap<>();
private final Map<String, String> hm = new HashMap<>();
@Setup
public void setup() {
keys = new String[size];
for (int i = 0; i < size; i++) {
keys[i] = "key" + i;
hm.put(keys[i], "value" + i);
chm.put(keys[i], "value" + i);
}
}
private String randomKey() {
return keys[ThreadLocalRandom.current().nextInt(keys.length)];
}
@Benchmark
public String chmGet() {
return chm.get(randomKey());
}
@Benchmark
public String hmGet() {
return hm.get(randomKey());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment