nvelocity的单例用法

目前nvelocity的典型用法是

//创建一个模板引擎

VelocityEngine vltEngine=new VelocityEngine();

//文件型模板,还可以是assembly,则使用资源文件

vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER,”file”);

//模板存放目录

vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,Server.MapPath(“~/Template”));

vltEngine.Init();

这对于调用次数很少,或者只在程序初始化调用的情形是适合的,但是对于网站这种要多次调用模板的系统显得就不太合适。可以看一下VelocityEngine的init方法实现:

/*
* This is the primary initialization method in the Velocity
* Runtime. The systems that are setup/initialized here are
* as follows:
*
* <ul>
* <li>Logging System</li>
* <li>ResourceManager</li>
* <li>Parser Pool</li>
* <li>Global Cache</li>
* <li>Static Content Include System</li>
* <li>Velocimacro System</li>
* </ul>
*/
public virtual void init() {
lock(this) {
if (initialized == false) {
info("************************************************************** ");
info("Starting NVelocity v0.4.1");
info("RuntimeInstance initializing.");
initializeProperties();
initializeLogger();
initializeResourceManager();
initializeDirectives();
initializeParserPool();


/*
* initialize the VM Factory. It will use the properties
* accessable from Runtime, so keep this here at the end.
*/
vmFactory.initVelocimacro();


info("NVelocity successfully started.");


initialized = true;
}
}
}

这其中包含了大量的对配置文件的读取,解析工作,工作日志记录等操作。其中还用到了反射等比较耗费性能的操作。

通过下面测试代码

Stopwatch stw = new Stopwatch();

stw.Start();

for (int i = 0; i < 100; i++)

{

var vltEngine = new VelocityEngine();

vltEngine.Init();

}

stw.Stop();

Console.WriteLine(stw.ElapsedMilliseconds);

可以发现,运行时间为7833毫秒,这是不能接受的。

其实NVelocity提供了单例的方法供我们调用,可参考官网的介绍(http://velocity.apache.org/engine/devel/developer-guide.html#singleton):

This is the legacy pattern, where there is only one instance of the Velocity engine in the JVM (or web application, depending) that is shared by all. This is very convenient as it allows localized configuration and sharing of resources. For example, this is a very appropriate model for use in a Servlet 2.2+ compliant web application as each web application can have its own instance of Velocity, allowing that web application's servlet to share resources like templates, a logger, etc. The singleton is accessable via theorg.apache.velocity.app.Velocityclass, and and example of use:


这样,将NVelocity的初始化放到静态构造函数中执行,只执行一次,可以保证性能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值