//创建一个模板引擎
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的初始化放到静态构造函数中执行,只执行一次,可以保证性能