当前位置: 首页 > 后端技术 > Java

Java性能优化影响性能的细节(三)从

时间:2023-04-01 14:40:16 Java

ArrayList到HashSet的一次性优化1.前言最近同事分享了一个遍历List判断元素是否存在的优化技巧。个人实验的一波还是很nb的。(一)本地实验结果1.环境信息jdk1.8测试工具:JMH1.22测试机:mbp16C32G2。测试结果在相同的10000个元素的情况下,HashSet比ArrayList快约7660倍。虽然在实验之前就知道HashSet肯定比ArrayList快,但是结果还是超出了预期。*测试结果(根据吞吐量测试):*BenchmarkModeCntScoreErrorUnits*perfTuning.TestListAndHashSet.checkArrayListWithContainsthrpt524.929±9.703ops/ms*perfTuning.TestListAndHashSet.checkArrayListWithIndexthrpt525.505±fashAndning1SetperListperfTunings/1.8.checkArrayList523.496±3.172ops/ms*perfTuning.TestListAndHashSet.checkHashSetthrpt5191505.153±9573.444ops/ms2.测试代码(1)测试源码考虑了极端情况,待判断的元素默认放在末尾。/***@Author:allen*@Date:2022/2/165:45pm*@Description:ArrayList和HashSet各种场景判断元素是否存在的性能对比**测试结果:*BenchmarkModeCntScoreErrorUnits*perfTuning.TestListAndHashSet.checkArrayListWithContainsthrpt524.929±9.703ops/ms*perfTuning.TestListAndHashSet.checkArrayListWithIndexthrpt525.505±1.811ops/ms*perfTuning.TestListAndHashSet.checkArrayListWithIteratorthrpt523.496±3.172ops/ms*perfTuning.TestListAndHashSet.checkHashSetthrpt5191505.153±9573.444ops/ms*/@State(Scope.Benchmark)publicclassTestListAndHashSet{publicstaticfinalHashSethashSet=newHashSet();publicstaticfinalArrayListarrayList=newArrayList();/***构建测试集合HashSet和ArrayList,均存储10001个元素,将待判断元素添加到最后*/@Setup(Level.Trial)publicvoidinit(){for(inti=0;i<10000;i++){hashSet.add(UuidUtil.getStrUuid());}hashSet.add("hashSet-test");for(inti=0;i<10000;i++){arrayList.add(UuidUtil.getStrUuid());}arrayList.add("arrayList-test");}/***HashSet通过定位key的hash值来查找,时间复杂度为O(1)*@returnBoolean*/@Benchmark@BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.MILLISECONDS)publicBooleancheckHashSet(){returnhashSet.contains("hashSet-test");/***通过迭代器遍历ArrayList逐一比较,时间复杂度为O(n)*可以查看编译后的字节码,使用迭代器遍历*@returnBoolean*/@Benchmark@BenchmarkMode(Mode.吞吐量)@OutputTimeUnit(TimeUnit.MILLISECONDS)publicBooleancheckArrayListWithIterator(){for(Strings:arrayList){if(s.equals("arrayList-test")){returntrue;}}返回假;}/***通过index手动遍历ArrayList逐一比较,时间复杂度为O(n)*@returnBoolean*/@Benchmark@BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.MILLISECONDS)publicBooleancheckArrayListWithIndex(){for(inti=0;i