首页 > 其他 > 详细

JMH之三种常见Map性能对比

时间:2020-05-05 15:46:03      阅读:73      评论:0      收藏:0      [点我收藏+]

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方法性能近似。

技术分享图片

 

JMH之三种常见Map性能对比

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!