//

OPTIMIZING ASP.NET MVC SITES

In this article we discuss about four ways of optimizing ASP.NET MVC sites

In this article we discuss about four ways of optimizing ASP.NET MVC sites:

  • Caching
  • Child actions
  • Asynchronous actions
  • Content bundling and minification

Introduction

There are three primary players involved when it comes to optimization:

  • Server - Respond as faster
  • Client - Render page as faster
  • Internet - Send server's response to the client faster

When it comes to optimization, we don't have much control over the internet, but we could reduce the amount of requests. Client-side code can be optimized by ## content bundling and## minification. Common server tasks include:

  • Interacting with database
  • Logic & data manipulation
  • Rendering HTML to the browser

Optimizing database interactions

  • Optimizing data for a limited period of time (caching)
  • raw data
  • fully rendered pages
  • pieces of pages
  • Interacting with the database on a separate thread

Output caching

  • Caching fully rendered HTML
  • Caching part of the HTML
  • caching the raw data
using System.Web;
using System.Web.Optimization;

namespace Auction
{
     public class BundleConfig

     // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
     public static void RegisterBundles(BundleCollection bundles)
     {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                                     "~/Scripts/jquery-{version}.js"));
        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                                     "~/Scripts/jquery-ui-{version}.js"));
        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                                     "~/Scripts/jquery.unobtrusive*",
                                     "~/Scripts/jquery.validate*"));

Microcaching

Caching a for a very short period time like one second. This is required in instances like reducing thousands of database queries per second. This reduces the bottleneck for database access.

Child Controllers/ Child Actions

A Child Action in MVC is similar to a User Control in ASP.Net web forms. It allows for a controller to execute for a portion of the rendered area of a view, just like in Web Forms where you can execute a UserControl for a portion of the rendered area of a page. Child Actions can be very powerful especially when you want to have re-usable controller code to execute that you otherwise wouldn't want executing inside of your view. This makes unit testing simpler because only controller code need to be tested, not the code in a view.

Asynchronous Actions

When there's a long-running operation, you can't apply output caching. Asynchronous actions can be used to resolve this problem by scaling your site for more concurrent users.

ASP.NET Thread Pooling

When a request is made on your ASP.NET website, it calls a vacant thread from the thread pool. If there are lots of requests, and the thread pool runs out of free threads, your website will stop responding. To mitigate this issue, asynchronous actions can be used to queue the requests.

Thread pool

When to use asynchronous controller

  • Long-running operations (eg:- longer than a second)
  • When a user may cancel a long-running operation
  • I/O intensive or network related operations (efficiency)

When NOT to use the asynchronous controller

  • Short running operations
  • CPU intensive operations
  • Simple operations (simplicity)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
sing System.Web;
using System.Web.Mvc;
namespace Auction.Controllers
{
   public class SearchController : AsyncController
   {
     public async Task<ActionResult> Auctions(string keyword)  
     {  
        var auctions = await Task.Run<IEnumerable<Models.Auction>>(
          () =>
          {
              var db = new Models.AuctionDataContext();
              return db.Auction.Where(x => x.Title.Contains(keyword)).ToArray();
          });
              
          return Json(auctions, JsonRequestBehavior.AllowGet);
     }
   }
}

4. Bundling and minification

Modern browsers limit open connection to 6. Rendering stops to wait for some scripts to finish downloading. Bundling(reduces the number of files) and minification(makes files smaller) can be used for reducing page load times. .NET framework provides System.Web.Optimization library for this purpose.

default_apppool_sql

Bundling

Bundling compiles multiple files into one request: You can register your bundles on the ## BundleConfig.cs file of App_Start folder.

using System.Web;
using System.Web.Optimization;

namespace Auction
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));

Note that line 15 uses a version placeholder and line 19 uses a wild card to look for similar files. Styles and script files should be references on _Layout.cshml file.

@ViewBag.Title - My ASP.NET MVC Application

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

Set the debug flag to false on your Web.config file

<system.web>
  <compilation debug="false" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  <authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
  </authentication>