|  | 级别: 初级 Harvey W. Gunther (hgunther@us.ibm.com), 资深性能分析师,WebSphere 产品开发, IBM
2002 年 4 月 01 日 有两种不同的方法用来创建 Javabean。一种方法是使用 new 来创建对象实例,而另一种方法是使用 java.beans.Beans.instantiate() 来创建新对象。然而,使用 Beans.instantiate() 会给性能带来负面影响,因为这种方法将在文件系统上搜索那个对象的一个序列化版本。如果找到序列化对象,则装入它。如果找不到它,则创建它。
读者:
架构设计师、开发人员
产品:
WebSphere Application Server
版本:
3.0.2.x、
3.5.x、
4.0
平台:
全部
关键字:
Servlet、
JSP 和 EJB、
bean、
Javabean
主题:
API 或接口、EJB、性能、可伸缩性
摘要
有两种不同的方法用来创建 Javabean。一种方法是使用 new 来创建对象实例,第二种方法是使用
java.beans.Beans.instantiate() 来创建新对象。然而,使用
Beans.instantiate() 会给性能带来负面影响,因为这种方法将在文件系统上搜索那个对象的一个序列化版本。如果找到序列化对象,则装入它。如果找不到它,则创建它。
建议
方法
java.beans.Beans.instantiate() 将通过从磁盘检索 bean 的序列化版本来创建一个新的 bean 实例,或者在序列化形式不存在时,创建一个新 bean。性能最佳的选项是创建一个新对象实例而不是用
Beans.instantiate() 。下面的代码样本说明了该选项。
使用 new SomeClass() 来创建新对象实例
public class WayToGoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int hitCount = 0;
// using new to create the instance
PingBean ab = new PingBean();
ab.setMsg("Hit Count: " + hitCount++);
req.setAttribute("ab", ab);
getServletContext().getRequestDispatcher("/servlet/PingServlet2ServletRcv").forward(req,res);
}
}
|
应被取代的方法
就性能角度而言,使用应被取代的方法
java.beans.Beans.instantiate ,就是每次调用
Beans.instantiate 方法时,都对文件系统进行检查以获取 bean 的序列化版本。通常,在您 Web 请求的关键路径中此类磁盘活动的开销很大。如前所述,为了避免此类开销,只要按照
建议中所显示的那样使用“new”方法来创建实例。下面的代码样本显示了创建类的实例的错误方法。图 1 说明了两个实现对性能的影响。
避免使用 java.beans.Beans.instantiate()
public class BadNewsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// this illustrates using Beans.instantiate() -- you do not want to implement this way
PingBean ab = (PingBean)Beans.instantiate(this.getClass().getClassLoader(),"web_prmtv.PingBean");
ab.setMsg("Hit Count: " + hitCount++);
req.setAttribute("ab", ab);
getServletContext().getRequestDispatcher("/servlet/PingServlet2ServletRcv").forward(req,res);
}
}
|
|
|
图 1:使用 new 而不是用 Beans.instantiate() 对性能的影响
|
|
参考资料
关于作者  | |  |
姓名:Harvey W. Gunther
职务:资深性能分析师
部门:WebSphere 产品开发
公司:IBM
地点:美国北卡罗莱那州罗利(Raleigh)
电子邮件:
hgunther@us.ibm.com
|
对本文的评价
|  | IBM 公司保留在 developerWorks 网站上发表的内容的著作权。未经IBM公司或原始作者的书面明确许可,请勿转载。如果您希望转载,请通过 提交转载请求表单 联系我们的编辑团队。 |