Created
July 29, 2021 16:27
-
-
Save apangin/3c48f128c503bc8d25e27b66f78458a7 to your computer and use it in GitHub Desktop.
ConcurrentHashMap vs. HashMap performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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