ASP.Net MVC Performance Tuning - Removing the WebForms View Engine

Hackered
Thursday, April 30, 2015
by Sean McAlinden

When working on ASP.Net MVC applications various performance issues can easily creep up on you, before you know it your awesome app is starting to annoy the hell out of you - not to mention your users.

If you create a vanilla ASP.Net MVC application and launch the home page a whole load of things are happening within your application including rendering the actual web page.

By default the vanilla ASP.Net MVC home page rendering includes the following:

  • Look for the Index view in the WebFormViewEngine cache
  • Look for the Index view in the RazorViewEngine cache
  • Look for the _LoginPartial view in the WebFormViewEngine cache
  • Look for the _LoginPartial view in the RazorViewEngine cache
  • Try to Load the _LoginPartial view using the WebFormViewEngine
    • Look in ~/views/home/_LoginPartial.aspx
    • Look in ~/views/home/_LoginPartial.ascx
    • Look in ~/views/shared/_LoginPartial.aspx
    • Look in ~/views/shared/_LoginPartial.ascx
  • Load the _LoginPartial view and home page using the RazorEngine

As you can see there is a great deal happening, unfortunately this does add a great deal of overhead to the application, more noticeable as your app grows and the number of partials etc. are added to a view.

If you are building a purely MVC application and do not require the WebFormViewEngine then you can save a lot of overhead with a couple of lines of code.

Get rid of that darn WebFormViewEngine

Ok, so my days of webform development are many years behind me now so lets get rid of it...

This needs to run at startup, possibly in your Global.asax or ideally in a start up class which is called from your Global.asax

const string CsFileExtensions = "cshtml";

ViewEngines.Engines.Clear();

var razorEngine = new RazorViewEngine() { FileExtensions = new[] { CsFileExtensions } };

ViewEngines.Engines.Add(razorEngine);

As you can see I've added in another little sneaky perf improvement, I'm 100% sure my days of VB.Net are well behind me so I'm helping razor out a little and letting it know, just incase :)

Will this really make much difference?

Yes, it really will.

Obviously we will all see various levels of improvement so the following is based on what I can see within my development ecosystem.

On the simple vanilla home page I see a consistent improvement of around 5 milliseconds and yes, this sounds quite insignificant at this point.

On another site I am working on where the views are complex, have numerous tabs which are loading numerous partials, removing the WebFormViewEngine has helped trim off 100's of milliseconds which is visibly noticeable.

Conclusion

For no real downside other than a marginal hit on your application startup routine, there is no reason to keep the WebFormViewEngine unless you need it... so get rid of it and don't look back.