读书人

Spring的获取Bean的性能测试

发布时间: 2012-10-27 10:42:26 作者: rapoo

Spring的获取Bean的性能测试。

package com.liuxt.bean;

import junit.framework.TestCase;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StopWatch;

public class ComputerTest extends TestCase {
?
?public static void main(String[] args) {
??
??AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
????new String[] { "bean/ComputerBean.xml" });
??ComputerBean computer1=(ComputerBean)ctx.getBean("computer");
??ComputerBean computer2=(ComputerBean)ctx.getBean("computer");
??System.out.println("computer1===computer2:"+(computer1==computer2));
??
??testGetBeanFromSpring(ctx);
??testNewInstaniate();

??ctx.destroy();
?}

?private static StopWatch testGetBeanFromSpring(AbstractApplicationContext ctx) {
??StopWatch stopWatch=new StopWatch();
??stopWatch.start();
??ComputerBean computer=(ComputerBean)ctx.getBean("computer");
??for(int i=0;i<100000;i++){
???computer=(ComputerBean)ctx.getBean("computer");
???computer.sum(i,i);
??}
??stopWatch.stop();
??System.out.println("100000 gets took "+stopWatch.getTotalTimeMillis()+" ms");
??return stopWatch;
?}

?private static void testNewInstaniate() {
??ComputerBean computer3;
??StopWatch stopWatch=new StopWatch();
??stopWatch.start();??
??for(int i=0;i<100000;i++){
???computer3=new ComputerBean();
???computer3.sum(i,i);
??}
??stopWatch.stop();
??System.out.println("100000 gets took "+stopWatch.getTotalTimeMillis()+" ms");
?}

}

?

测试的前提条件:

?JDK:java version "1.6.0_13"

winxp? cpu:2.6Ghz

?

测试结果:

? computer1===computer2:false
100000 gets took 907 ms
100000 gets took 0 ms

?

不知道为什么差距这么大。

请大家帮忙解释一下啊。。。期待中。

?

1 楼 airlink 2010-01-10 建议你再加个0来循环。
我的测试结果是10倍以上的差距。

spring的获取过程包括了反射和查找bean,其中反射占了大部分时间,这可以加一个用反射创建bean的测试来证明。

可以看看这个帖子:
http://www.iteye.com/topic/266759?page=2

2 楼 zhangjunji111 2010-01-18 airlink 写道建议你再加个0来循环。
我的测试结果是10倍以上的差距。

spring的获取过程包括了反射和查找bean,其中反射占了大部分时间,这可以加一个用反射创建bean的测试来证明。

可以看看这个帖子:
http://www.iteye.com/topic/266759?page=2



java6反射应该很快了呀?

读书人网 >软件架构设计

热点推荐