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来循环。