Render partial view to string benchmark

ASP.NET MVC logo

As I mentioned in my previous article about how to render an ASP.NET MVC View to a string, there are several methods to do it and they probably are quite different performance-wise. Well, this time I've got some benchmarks.  :)

So, I threw together a sample ASP.NET website with the three different methods. To recap:

  • My hackish way of creating a fake HttpResponse on a simple StringBuilder and then rendering the target view inside that context. The result of the view will be stored in the string builder whose contents can then be accessed directly.
  • The clean way of instantiating the view as a control and rendering it using the standard WebForms methods. This only works on WebForms controls of course, but looks very fast and the code is simple.
  • Or, applying a filter to the current HttpResponse and filtering the target view's output. This looks better than my approach, but requires at least one "Flush" call on the response.

I ran a couple of tests using IIS 7 (the one included in Windows 7): each test has been run 5 times, with 1000 iterations and a certain number of "warm up" invocations. These are the results:

View to string benchmark results

As you can see, the "control instantiation" method is way faster than the other two. In fact, this is to be expected since it goes directly through the rendering method built in WebForms and nothing else. Unexpectedly the response filtering method is almost twice as slow as the other one. The "fake response", even if it looks slow and clunky, actually doesn't perform all too bad.

Anyway, the graphs shows times for 5000 repetitions: that means that, in the slowest case, rendering a view to string takes at most 0.03 ms! That makes the whole benchmarking pretty pointless, at least if you're not rendering a ton of views to string in your application. Anyhow, here's the code and here the results on a google spreadsheet.