Monday, November 19, 2012

How to Improve ASP.Net MVC 3 View Performance ?

What is a View ?
  • Incoming browser requests are mapped to controller actions
  • A controller action might return a View
  • View handles the display of the data
  • Most often the Views are created from the ViewModel data

MVC

How to Improve View Performance ?

Tip 01 :  Run in Release Mode
  • You should always make sure that your application is Compiled in Release Mode
Compiled in Release Mode
  • Your Web.config file Must Looks Like below on Production
         <compilation debug="false" targetFramework="4.0">
         <assemblies>

        </assemblies>
     </compilation>

   Why This Needs ?

      #  MVC Will Not do any View Look-up Caching if you are running your application
            in Debug Mode

Tip 02 : Use only the View Engines that you need

  • MVC framework supports having multiple view engines
  • Can Configured simultaneously in your application
  • And will query each in turn when it is trying to find a View
  • In MVC 3 we register two view engines by default (WebForms and Razor)
  • There is no reason to pay the performance price for something you are not using
  • So make sure you specify only the view engines you need in your Global.asax file
         Global.asax  file Looks Like below :

      protected void Application_Start()
        {
          ViewEngines.Engines.Clear();
          ViewEngines.Engines.Add(new RazorViewEngine());//add razor view engine
        }

Tip 03 Avoid passing null ViewModels to Views

     When it Happens ?
  • You pass in a null ViewModel to a View that uses strongly-typed html helpers 
           Such as in the View :

              @model PawLoyalty.ViewModels.Product
          
      @{
                
              @Html.TextBoxFor(m => m.ProductName); 
       
       }
  • This frequently happens in Insert (Add) scenarios

    Why is it Bad ?
  • Strongly-typed html helpers like above,
  • Will try to emit the value of the ViewModel using the provided expression
  • However when something along the expression chain is null a NullReferenceException will be thrown,
  • When the expression gets evaluated,
  • MVC’s expression evaluator catches the exception
  • But on a page with multiple such html helpers the cost of the exception adds up
  • You can avoid that cost by always passing an instance of the ViewModel to the View

    Bad Way :

        [HttpGet]
        public ActionResult Add() //get empty data for user input operation
        {
            return View();  //here the model instance defaults to null
        }

    Best Way :

        [HttpGet]
        public ActionResult Add()//get empty data for user input operation
        {
          return View(new Product());//here the ViewModel Product has been sent
        }



Tip 04 Uninstall URL Rewrite if you don’t use it

  When it Happens :
  • Your IIS server has the URL Rewrite module installed
  • When you are running ASP.NET MVC 3,
  • None of the applications on the server are using it

            What is URL Rewrite ?

               #  Enables Web administrators to create powerful rules to implement URLs
               #  That are easier for users to remember and easier for search engines to find

Why is it Bad ?

  • When performing URL generation (e.g : Html.ActionLink)
  • MVC 3 checks to see if the currently requested URL has been rewritten by the URL Rewrite module
  • The act of checking need significant computing power to solve (because it involves checking server variables)
  • So if you are not using URL Rewrite you should Turn it Off (Uninstall)

                   How to Uninstall URL Rewrite ?

                       # Win 7 --> Controller Panel --> Programs and Features -->

Uninstall URL Rewrite


             Important Note :  MVC 2 always performs this check.So turning
                                         URL Rewrite off  (uninstall)  will not make a difference


Tip 05 Enabling Output Caching

    What is Output Caching ?

  • Enables you to cache the content returned by a controller action
  • The same content does not need to be generated each and every time the same controller action is invoked
  • Caching enables you to avoid performing redundant work on the Server
  • Can apply for either individual controller action or an entire controller class

   How to Do That ?

  • Using [OutputCache] attribute

    Lets take a simple Example

    public class HomeController : Controller
    {
      [OutputCache(Duration = 10, VaryByParam = "none")] //cached for 10 seconds
      public ActionResult Index()
      {
          return View();
      }
    }

   When to Use it ?
  • Read operations Only

  When Not to Use it ?
  • Writes operations.Such as Update,Delete and Inserts 
  • Pages which are User Specific.e.g. shopping cart page

Summery of Performance Gain Chart :

Performance Gain Chart

                        Pages/Sec - How many pages can load per second

                        Page Time (ms) - How long will it take to load a page

                        Base - Page that has not done any performance gain operations

Conclusion
  • You can see that highest performance gain can get by using OutputCache operation
  • But OutputCache having it's own Limitations
  • I will explain more about MVC caching in My future blog post
  • If your page is load under 1 second then you may not worry too much about performance gain

I hope this helps to You.Comments and feedback greatly appreciated.

Happy Coding.

MVC Related Articles


27 comments:

  1. Replies
    1. Hi Claudio,

      Thanks for your appreciation.
      Do Keep in Touch.

      Delete
  2. like this.

    -Peter Ernst-

    ReplyDelete
    Replies
    1. Hi Peter,

      Thanks for your feedback.
      Do Keep in Touch.

      Delete

  3. Good article,very useful, thanks. ;)

    -Henrique Adriano -

    ReplyDelete
  4. Nice article and helpful.

    -Askar-

    ReplyDelete
    Replies
    1. Hi Askar,

      Thanks for your response.
      Do Keep in Touch.

      Delete
  5. Replies
    1. Hi Mukesh,

      Awesome man, let me know if you have any questions...

      Delete
  6. Replies
    1. Hi hacky,

      Thanks for your feedback.
      Do Keep in Touch.

      Delete
  7. Hi,

    That is a great piece for work for the beginners.
    I liked the stuff.

    With Regards,
    Vishnu Nadesh

    ReplyDelete
  8. Very useful article. Thanx.

    -smita naik-

    ReplyDelete
    Replies
    1. Hi smita,

      Thanks for your feedback.
      Do Keep in Touch.

      Delete
  9. I would add one from the top of my head:

    If you are using a remote Session provider, disable Session for controllers that do not use it,
    or limit its scope with the SessionStateAttribute and System.Web.SessionState.SessionStateBehavior.

    Cheers.

    -Valeriano Tórtola Luis-

    ReplyDelete
    Replies
    1. Hi Valeriano,

      Thanks for your Tip.
      Do Keep in Touch.

      Delete
    2. If you are using InProc session, the Session object is just a Dictionary that is kept in memory. But, if you are using a remote session provider, like for example the one that uses SQL Server, a Session Server, or Azure Caching, every time that you load the page, the session is retrieved and deserialized, and when the page is about to exit,
      it is serialized and saved. Of course, this implies a delay.

      Also, if in your application the site can do multiple parallel requests, using Session won't allow the parallelism and the requests will be handled in serial fashion.

      http://tech-journals.com/jonow/2011/10/22/the-downsides-of-asp-net-session-state

      --Valeriano Tórtola Luis--

      Delete
  10. Thanks a lot sampath, This article is very use full. keep the good work.

    ReplyDelete
    Replies
    1. Hi RAZIN,

      Thanks for your appreciation.
      Do Keep in Touch.

      Delete
  11. Replies
    1. Hi chandima,

      Thanks, I’m glad you enjoyed it!

      Delete
  12. Nice Article its very useful for me

    ReplyDelete
  13. When testing performance, be sure to use an application performance monitoring (APM) tool so you can track page load times, slow database queries, etc for every request in your app. You can also use them to see interactions with web services, caching, queues, etc. They are really invaluable tools for performance testing and tuning!

    Thanks,
    Matt Watson with Stackify APM (http://www.stackify.com)

    ReplyDelete

Thanks for your Feedback.