JMH之三种常见Map性能对比

JMH之三种常见Map性能对比

测试代码

@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class TestMap_JMH {
    static Map hashMap = new HashMap();
    static Map synMap = Collections.synchronizedMap(new HashMap<>());
    static Map conMap = new ConcurrentHashMap();

    @Setup
    public void setup(){
        for (int i=0;i<1000;i++){
            hashMap.put(Integer.toString(i),Integer.toString(i));
            synMap.put(Integer.toString(i),Integer.toString(i));
            conMap.put(Integer.toString(i),Integer.toString(i));
        }
    }

    @Benchmark
    public void hashMapGet(){
        hashMap.get("4");
    }

    @Benchmark
    public void synMapGet(){
        synMap.get("4");
    }

    @Benchmark
    public void conMapGet(){
        conMap.get("4");
    }

    @Benchmark
    public void hashMapSize(){
        hashMap.size();
    }

    @Benchmark
    public void synMapSize(){
        synMap.size();
    }

    @Benchmark
    public void conMapSize(){
        conMap.size();
    }

    public static void main(String[] args) {
        Options opt = new OptionsBuilder().include(TestMap_JMH.class.getSimpleName())
                .forks(2).build();
        try {
            new Runner(opt).run();
        } catch (RunnerException e) {
            e.printStackTrace();
        }
    }
}

测试结果

Benchmark                 Mode  Cnt     Score    Error   Units
TestMap_JMH.conMapGet    thrpt   10   178.179 ± 17.030  ops/us
TestMap_JMH.conMapSize   thrpt   10   777.735 ± 35.146  ops/us
TestMap_JMH.hashMapGet   thrpt   10   168.352 ±  7.346  ops/us
TestMap_JMH.hashMapSize  thrpt   10  1434.474 ± 36.197  ops/us
TestMap_JMH.synMapGet    thrpt   10    40.580 ±  1.227  ops/us
TestMap_JMH.synMapSize   thrpt   10    44.711 ±  1.657  ops/us

结论

使用了两个线程进行测试,由于HashMap完全不关心线程安全,所以他的性能是最好的。
HashMap经过同步的包装后,性能出现了急剧的下降。
ConcurrentHashMap的get方法和HashMap的get方法性能近似。

原文地址:https://www.cnblogs.com/beanbag/p/12830482.html