• Asp.net MVC初次加载时为什么会很慢


    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;
                }
            }

     一下是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

  • 相关阅读:
    操作系统,,,也考完了【流坑】
    认真地搭建python开发环境
    NumPy 上手一个例子 vectorsum.py
    数字图像处理、、考完了
    Intel系列CPU的流水线技术的发展
    JSON序列化为实体对象
    一个丝滑的全屏滑动返回手势
    Swift项目兼容Objective-C问题汇总
    OC 九宫格布局
    SDWebImage 新版接口使用方法
  • 原文地址:https://www.cnblogs.com/hjblog/p/2052978.html
Copyright © 2020-2023  润新知