关于BeanUtil.copyProperties性能

BeanUtil.copyProperties 方法确实很方便,代码写出来非常优美,不会有很多的get set,但由于用到反射,可能存在潜在的性能问题。因此对spring 和 commons的BeanUtil.copyProperties进行了对照测试,代码大致如下:
Java代码   收藏代码
    @Test  
        public void copyPropertiesTest() throws IllegalAccessException, InvocationTargetException {  
              
            po = new PromotionPO();  
            Timestamp now = new Timestamp(System.currentTimeMillis());  
            model = RetailmodelFactory.eINSTANCE.createPromotion();  
    //get/set  
            Long startTime = System.currentTimeMillis();  
            for (int i = 0; i < LOOP_NUMBER; i++) {  
                model.setCode("code");  
                model.setDescription("haha");  
                model.setDiscount(5.4);  
                model.setEndTime(now);  
                model.setID(39578395L);  
                model.setPriority(1);  
                model.setPromotionType(3);  
                model.setStartTime(now);  
                model.setSupplierID("123245L");  
            }  
            Long endTime = System.currentTimeMillis();  
            traditionalCopyTIme = endTime - startTime;  
              
    //spring  
            startTime = System.currentTimeMillis();  
            for (int i = 0; i < LOOP_NUMBER; i++) {  
                BeanUtils.copyProperties(model, po);  
            }  
            endTime = System.currentTimeMillis();  
            springCopyPropertiesTime = endTime - startTime;  
      
    //commons         
            startTime = System.currentTimeMillis();  
            for (int i = 0; i < LOOP_NUMBER; i++) {  
                org.apache.commons.beanutils.BeanUtils.copyProperties(po,model);  
            }  
            endTime = System.currentTimeMillis();  
            commonsCopyPropertiesTime = endTime - startTime;  
              
            logger.info("normal copy Time: " +  traditionalCopyTIme + "ms.");  
            logger.info("Spring BeanUtil copy Time: " +  springCopyPropertiesTime + "ms.");  
            logger.info("Commons BeanUtil copy Time: " +  commonsCopyPropertiesTime + "ms.");  
        }  


当 LOOP_NUMBER = 50000时(即执行50000次copy),结果如下:
编号set/getSpring BeanUtilCommons BeanUtil
162ms1703ms63860ms
116ms1359ms62328ms
116ms1359ms63047ms
10ms1390ms63047ms
116ms1375ms62266ms


可看出Commons BeanUtil的copyProperties 性能最差,几乎不能忍受。spring的copyProperties有可能在接受范围内。直接set/get虽然丑陋,但是性能确实非常好,几乎可以忽略。
接下来对spring和commons两种不同实现进行分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值