程序运行时间之我见

类别:Java 点击:0 评论:0 推荐:

    最近很关注XML,关心各种流行解析技术的效率,在测试程序运行时间的时候,遇到一些困难,下面先看看我提出的问题吧。
   
-----------------------------------------------------------------------------

    在一个类中,有一个叫做test()的方法需要被JSP端调用(test()主要任务是System.out.print()),于是在test()方法开始的地方加上"long lasting =System.currentTimeMillis(),"在结束的地方加上"System.out.println("运行时间:"+(System.currentTimeMillis() - lasting)+" 毫秒")"。

    然后把test()方法改成main()方法,以便单独测试类,JSP端代码作出相应调整以便访问main()方法。奇怪的事情发生了,经过反复测试,使用JSP访问main()方法消耗的时间为 451 毫秒,而单独运行这个类消耗的时间为 2864 毫秒。

    为什么会这样?是不是WEB容器的原因呢?
   
-----------------------------------------------------------------------------

    在一个人气很高的论坛上,我得到些解答,自己也总结了一些,请各位看官来发表意见:
   
    第一次请求JSP时,WEB容器将JSP发送到编译器,编译成Servlet。然后把该Servlet相关联所有类的联合体(我是这么认为的)缓存在WEB容器中,最后将响应结果返回给客户端,而JSP的所有后继请求,WEB容器将自动载入缓存,除非JSP经过修改,否则该JSP将不会被重新提交进行编译。而运行类就不一样了,每次运行都需要编译重新才行,所以要慢些了。
    另外,根据测试,在JSP端第一次被调用的时候,时间和单独运行类差不多,这也印证了上面的解释吧。

   
   
附上源程序
类:
package com.test;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;

public class MyXMLReader extends DefaultHandler{ 

 java.util.Stack tags=new java.util.Stack();

 public MyXMLReader(){
  super();
 }

 public static void main(String args[]){
 long lasting =System.currentTimeMillis();
  try{  
      SAXParserFactory sf  = SAXParserFactory.newInstance();
      SAXParser sp = sf.newSAXParser();
      MyXMLReader reader = new MyXMLReader();
      sp.parse(new InputSource("data.xml"),reader);
  }
  catch(Exception e){
   e.printStackTrace();
  }
  System.out.println("运行时间:"+(System.currentTimeMillis() - lasting)+" 毫秒");
 }

 public void characters (char ch[], int start, int length)
    throws SAXException
   {

  //从栈中得到当前节点的信息
   String tag=(String) tags.peek();
    if(tag.equals("NO") ){
   System.out.print("车牌号码:" +  new String(ch,start,length));
    }
    if(tag.equals("ADDR")){
   System.out.println("  地址:" + new String(ch,start,length));
    }
   }

 public void startElement(String uri, String localName, String qName, Attributes attrs){ 
 tags.push(qName);
 }
}

JSP:
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="com.test.*"%>

<%
    long lasting =System.currentTimeMillis();
%>
<html>
    <body>
<%
    String args[]={""};
    MyXMLReader.main(args);
%>
    </body>
</html> 


(请注意!引用、转贴本文应注明原作者:Rosen Jiang 以及出处:http://blog.csdn.net/rosen

本文地址:http://com.8s8s.com/it/it14538.htm