Wednesday 29 June 2011

ASP.NET MVC Mini-Profiler - First Impressions

This is a useful free profiler for ASP.NET MVC from the people at StackOverflow.com (a wonderful source of answers, and built using ASP.NET MVC).

The easiest way to install it in VS2010 is using NuGet

These snippets show one way to use it.

Site.Master (.ASPX view engine)

<script src="<%: Url.Content("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js") %>"  type="text/javascript"></script>
<%= MvcMiniProfiler.MiniProfiler.RenderIncludes() %> 

Global.asax.cs

A simple approach is to start and stop the profiler for each separate web request, for example:

using MvcMiniProfiler; 

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_BeginRequest()
        {
            if (Request.IsLocal)
                MiniProfiler.Start();
        }
        
        protected void Application_EndRequest()
        {
            if (Request.IsLocal)
                MiniProfiler.Stop();
        }
    }

In A Controller, for example


Create a separate MiniProfiler 'step' for any long processing steps that you want to profile:

var profiler = MiniProfiler.Current;
 
    // No need to check 'profiler' for null here, it's handled in profiler.Step()

    using (profiler.Step("Search"))
    {
        // Time-consuming stuff...
        DoLongSearch(xxx);
    }

Steps can be nested, and the profile output will show the step structure:

    using (profiler.Step("SearchAndUpdate"))
    {
        using (profiler.Step("Search"))
        {
            // Time-consuming stuff...
            DoSearch(xxx);
        }

        using (profiler.Step("Update"))
        {
            // Time-consuming stuff...
            DoUpdate(xxx);
        }
    }

Viewing the Output


When you navigate to a URL that causes the profiler to be called, the resulting view will contain a small MiniProfiler gadget at the top left. Click on it to get the timing detail.

Linq to SQL


You can use the MiniProfiler to profile database calls, including Linq to SQL - see this post. The profile information includes the elapsed time of each query and also warns of 'duplicate' SQL queries, both of which can help in optimizing application design.

2 comments:

  1. You don't need to (and shouldn't) check the profiler for null.

    The .Step("") extension method handles this gracefully.

    See here: http://samsaffron.com/archive/2011/06/09/+Profiling+your+website+like+a+true+Ninja

    ReplyDelete
  2. Many thanks cvallance, I'll amend the snippets.

    Jim

    ReplyDelete