java之for循环优化

/ 技术 / 0 条评论 / 900浏览

外小内大 耗时,比外大内小耗时少

   @Test 
    public  void testForWaiNei() {
        // 方法说明 : 测试内外循环
        // 1. 测试外循环比内循环小
        Long startTime = System.nanoTime();
        for (int  i = 0; i<100; i++){
            for ( int j = 0; j<1000000 ; j++){
                
            }
        }
        Long endTime = System.nanoTime();
        System.out.println("内大外小耗时: "+(endTime-startTime));
    }

提取无关的表达式,放在循环外面处理

如下把a*b提出for循环外处理会提升性能

@Test 
    public  void testForWuGuan() {
        // 方法说明 : 测试内外循环
        // 1. 测试外循环比内循环小
        int a = 10,b=12;
        Long startTime = System.nanoTime();
        for ( int j = 0; j<1000000 ; j++){
            j = j*a*b;
        }
        Long endTime = System.nanoTime();
        System.out.println("耗时: "+(endTime-startTime));
    }

消除循环终止判断时的方法调用

如下applyInfoMigrationList.size() 使用常量替代会提升性能

@Test 
    public  void testForWuXunHuanBianLiang() {
        String sql  = "select * from in_applyinfo where status_lookup_code='140' allow filtering";
        List<ApplyInfoMigration> applyInfoMigrationList = applyInfoDao.selectList(sql,ApplyInfoMigration.class );   // A实体
        int a = 10,b=12, c=a*b;
        Long startTime = System.nanoTime();
        for ( int j = 0; j<applyInfoMigrationList.size() ; j++){
            // j = j*c;
        }
        Long endTime = System.nanoTime();
        System.out.println("耗时: "+(endTime-startTime));
    }

对异常进行优化

如下 try,catch放循环外面会提升性能

@Test 
    public  void testForException() {
        // 方法说明 : 测试for循环优化
        Long startTime = System.nanoTime();
        for ( int j = 0; j<1000000 ; j++){
            try {
                
            }catch (Exception e){
                
            }
        }
        Long endTime = System.nanoTime();
        System.out.println("耗时: "+(endTime-startTime));
    }

使用map

如下 //map查询测试

        int mapNumber = 0;
        Map<Integer, Member> map = new HashMap<>();
        for(Member m1:list1){
            map.put(m1.getId(), m1);
        }
        for(Member m2:list2){
            if(m2.getName()==null){
                Member m = map.get(m2.getId());
                if(m!=null){
//                 System.out.println(m2.getId()+" Name 值为空!!!");
                    mapNumber++;
                }
            }
        }