zoukankan      html  css  js  c++  java
  • 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自动化测试-使用第三方python库技术实现
    JMeter目录结构
    JMeter Http请求之content-type用法
    JMeter生成性能报表-Windows环境和Linux环境
    JMeter4.0 IF Controller
    c++ 初始化列表和构造函数初始化区别
    关于C++ 中 thread 的拷贝构造函数
    函数的参数类型 指针和指针的引用的区别
    window10 vs2013 SIFTGPU
    Qt使用双缓冲绘图时报错:pure virtual method called
  • 原文地址:https://www.cnblogs.com/hjblog/p/2052978.html
Copyright © 2011-2022 走看看