Asp.net MVC初次加载时为什么会很慢
2011-05-21 17:24 zhoujie 阅读(6324) 评论(14) 编辑 收藏 举报Asp.net MVC是一个不错的框架,最近开发一直使用。可是最近发现一个问题:MVC初次加载时很慢,有时我在默念计时到6,页面才显示出来,感觉上就比asp.net WebForm慢。因为以前的程序都是WebForm开发的,两相对比,感觉很明显。不过这只限于第一次,后续访问感觉上又比WebForm快,我想这是MVC输出的HTML简洁的缘故。
也许你会说,这不成问题,我自己充当第一个访问者就行了。可是问题在于公司的IIS服务器会定期回收应用程序池,一段时间后,又要经历第一次了。
昨天花了点时间翻了一下MVC2的源代码,最后Trace到如下代码是性能瓶颈:位于WebFormViewEngine.cs中的FileExits函数。
protected override bool FileExists(ControllerContext controllerContext, string virtualPath) {
try {
controllerContext.HttpContext.Trace.Write("FileExists");
object viewInstance = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(object));
controllerContext.HttpContext.Trace.Write("FileExistsEnd");
return viewInstance != null;
}
catch (HttpException he) {
if (he.GetHttpCode() == (int)HttpStatusCode.NotFound) {
// If BuildManager returns a 404 (Not Found) that means the file did not exist
return false;
}
else {
// All other error codes imply other errors such as compilation or parsing errors
throw;
}
}
catch {
return false;
}
}
try {
controllerContext.HttpContext.Trace.Write("FileExists");
object viewInstance = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(object));
controllerContext.HttpContext.Trace.Write("FileExistsEnd");
return viewInstance != null;
}
catch (HttpException he) {
if (he.GetHttpCode() == (int)HttpStatusCode.NotFound) {
// If BuildManager returns a 404 (Not Found) that means the file did not exist
return false;
}
else {
// All other error codes imply other errors such as compilation or parsing errors
throw;
}
}
catch {
return false;
}
}
一下是Trace截图:
如果是第一次修改后编译运行,就会收到一个2.46秒的等待!有时会更长,因为我测试的View和Controller都很简单。
原因分析:
Asp.net MVC 默认其实还是动态编译的,第一次时间都浪费在编译加载上了。
解决方法:
改为预编译。对于IIS定期回收的,还是没有好办法。我只能编个程序每隔20分钟访问一次,让MVC时刻保持活力!哈哈!
如何预编译MVC?
Q: Is there a way to precompile MVC application including code and views for deployment?
A: You need to install the Visual Studio Web Deployment add-in (see http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en) In your MVC solution, right click on the MVC project and select "Add Web Deployment Project..." (thanks to Jacques) --- running the command line utility using aspnet_compiler will also do the job. The command line is:(framework directory)\aspnet_compiler -v /virtualDirName outputdirectoryName
如何Trace?
web.config配置
<trace enabled="true" localonly="false"/>
访问跟踪信息:
http://web站点/应用程序/trace.axd