RenderAction vs RenderPartial performance - asp.net-mvc

According to Brad Wilson, RenderAction is slower than RenderPartial.
However, has anyone got any statistics that show the difference in performance?
I'm in the process of developing an application where pages are composed of "Widgets".
I have two choices:
Composition at the View Level
Call RenderAction for each widget. This is by far the easiest approach but does mean that we're performing a full MVC cycle for each widget.
Composition at the Controller Level
Compose one ViewModel for the page that contains the data we need for each widget. Call RenderPartial for each widget. This is much more complicated to implement but does mean we'll make only one MVC cycle.
I tested the above approaches with 3 different widgets on a page and the difference in render time was 10ths of a second (hardly worth worrying about).
However, has anyone got any test results more concrete than this, or perhaps experience trying both approaches?

I've recently worked on an application that was experiencing performance issues, and found a view that was making four calls to RenderAction, plus another one in the layout. I found that each call to RenderAction--even when I added in a dummy action that returned an empty view--took around 200-300ms (on my local machine). Multiply by the number of calls and you have a huge performance hit on the page. In my case there were four calls causing about a second of unecessary server-side overhead. By comparison, calls to RenderPartial were around the area of 0-10ms.
I would avoid using RenderAction wherever possible in favor of RenderPartial. The controller should be responsible for returning all necessary information. In the case of widgets, if you need multiple actions for several widgets, I would try composing them into one action so the RenderAction overhead only occurs once, though if your site performs adequately I'd keep them separate for a cleaner design.
Edit: I gathered this information using MiniProfiler and hitting the site. It isn't super accurate but it does clearly show the differences.
Edit: As Oskar pointed out below, the application in question likely had some intensive code that runs for each request in global.asax. The magnitude of this hit will depend on the application code, but RenderPartial will avoid executing another MVC cycle altogether.

I'd suggest 2 more options, both require to compose the view model at Controller level and both can work together (depending on the data)
Html.DisplayFor() - display templates
Helpers via extension methods
Option 2 works very well if you want to keep those widgets in different assemblies, after all they're just functions returning a string. I think it has also the best performance, but of course you lose the 'designer friendly' templates. I think it's important to consider the maintainability aspect, not only raw performance (until you really need it, and even then, caching is more helpful).
For small stuff (date or name formatting etc) i'd use helpers, since the html is usually a span with a class, for more complex stuff I'd use the display templates.

Related

Which is better - Output Caching 6 Child Actions or 6 DB queries using RenderPartial?

I am attempting to develop a cms system that will use tags to display similar content. For example, underneath the news section there will be articles, blogs, news and forum questions that share the same tags. There will be no more than 5 items in each list.
I am considering 2 options for displaying this related content and am wondering if developers with more experience than myself would recommend one over the other?
Speed is the primary goal, because we have equally maintainable ways of executing both options.
Option 1 - Output Caching RenderAction Results
For each 'similar content' section, render a child action on the corresponding controller and cache the output. This feels more in the spirit of MVC, and would be light on DB calls. But with 5 'similar content' lists, that would equal 6 full MVC cycles for each page request.
I've read that RenderAction can still be expensive, even though it has improved in the last couple of years.
Option 2 - RenderPartials with DB Queries for Each
Alternatively, for each 'similar content' section, we could query the db and use RenderPartial to display the output. Although this would require a small DB query for each section (5 items or less), I'm wondering how that would compare with the performance saved by NOT calling RenderAction.
I've frequently read how much faster RenderPartial is compared to RenderAction.
Essentially your choice boils down to which is faster: RenderAction with an already cached result or 5 DB queries?
When you look at it that way, you really are talking about one solution with no network latency and one solution with network latency (sending the query to the database and receiving a response). Any solution that removes network latency is de facto faster than an alternative with network latency.
Also, bear in mind that purists like to talk about how one thing or another is "slow" compared to some other way. Yes, child actions will always be slower than partials because child actions go through the whole routing infrastructure and then finally to the Razor template engine whereas partials just go directly to the Razor template engine. But, we're talking about highly optimized, compiled code running in memory. "Slower" is measured in milliseconds or even nanoseconds. Sure, those can add up over time, and if you did something crazy like render 50 child actions in a single view, you might see some noticeable performance loss, but this will typically not be an issue worth worrying about in 99.9999% of cases.
Just design your application in the way that makes the most sense for your application and stop worrying about a millisecond here or there.

What are the best practices for Asp.net MVC page construction, allowing for parallelism and efficiency?

I found it difficult to argue with anything in this critique of ASP.net MVC's framework for page composition.
http://www.matlus.com/problems-with-asp-net-mvc-framework-design/
Particularly these points:
No access to view or partial view instances
ViewData is your loosely typed information carrier
Controller is not really in control
Child Actions have no sense of the Request Context
Views are coupled to controllers
For small applications, I don't think that a lot of these prove to be much of a problem, but in large applications where you want to reuse a lot of shared components, or even if you just have a large application that depends on multiple backend sources of information to obtain all of the information necessary to render a view, it starts to break down.
Various half-solutions to these problems have been proposed but they do not appear to scale well or have undesirable design constraints.
Here is an example application scenario:
50% of page content is common across all pages within an application (header, footer, menus, etc.)
Your application may actually be comprised of multiple areas, each with their own controllers, etc. for independent development.
A number of the page elements (menus, page header information, footers, disclosures) that are in the common page content require one or more service calls to fill out the data for rendering.
Okay, so in asp.net mvc3, let's say that you decide that you want to share a common Razor layout that contains the 50% common UI markup. This assists with Separation of Concerns in that application developers don't need to be concerned about common ui and can focus on the logic and views specific to their domain of expertise.
However, this completely breaks down in the case that this shared layout needs data (some semblance of one or more model types) to render itself completely. You may have independent elements on the page that each need a particular data model, such as:
* primary menu model
* secondary menu model
* footer links model
* authorization model
* footer disclaimers model
And each of these models may have separate sources. So although you can share the template, there is not an easy way to share the logic to build each of these models -- and there is definitely not one that is generic, extensible, and performant that I have seen.
Some approaches to this problem that I have seen are:
Strongly type the common layout, which requires all view models to subclass a common base model class. (but there is no general solution to populating such a meta-model, and this is limiting in design and makes models huge and harder to test) Additionally, model population still falls to every controller, violating the Separation of Concerns and Single Responsibility Principle and complicating unit testing controllers by piling on lots of extra logic to populate the meta-model in addition to the view-specific model information.
Leave the common layout untyped, so you don't have to inherit from a common base model, but this requires you to use ViewData or ViewBag to communicate all of the disparate models that the template needs so you lose strong typing benefits and end up with a loose data contract. You still have the problem of a lack of a general solution to populating the meta-model and all that goes along with that.
Every controller has to subclass a common base controller class to support a common layout and model. Logic for building the common aspects of the meta-model goes here. But this is not always a desirable architecture or design constraint. This does at least resolve the Separation of Concerns issues.
Instead of a meta-model, use child actions via RenderAction() in your common layout to make reusable "portlet" style widgets that each know independently how to build their data model and provide it to their view. This is really good for Separation of Concerns, but has its own litany of downsides: views effectively making service calls during rendering via the child actions, child actions are completely unaware of the original request context, violates DRY principle as each child action is unaware of what has gone before it so each could make the same service calls over and over again in the same http request, and others. Imagine 20-30 elements of a page that all needed to invoke RenderAction() independently...
There are additional cases (some seen on stackoverflow as well) where there are other problems with RenderAction() as a solution. e.g. the fact that issuing multiple RenderAction() calls in a loop results in serial execution of all of those controller methods. There is no opportunity for parallelism with RenderAction(). I/O bound service calls in each child controller action cause the whole rendering process to wait on I/O. A controller only has knowledge of its immediate view and model and nothing has a complete picture of what is going to be inside the view in order to parallelize some operations.
The author of the above critique developed a different UI model on top of ASP.Net mvc called Quartz that allows a God Controller to have intimate knowledge of the views and can hand each of them a view model so has the opportunity to parallelize service calls in a central place to build those view models. I don't know if this is the best design to provide hooks for overcoming the problems but looks promising.
My question is, what is the best practice for building a complex application on top of ASP.Net MVC that cleanly solves these problems? I have thought of a couple possibilities (although none may be practical within ASP.Net MVC--that is TBD) but someone else must have ran into this already. What are the design patterns within ASP.Net MVC or what is coming down the pike that could make this a tractable problem?
Personally, I think that the advantages of using Child Actions via RenderAction outweigh the disadvantages.
You can create 'widget' sort of elements, and wrap up their logic in a controller action - this way the view calling the widget can remain quite ignorant of what the Child Action is doing and how it is doing it - leading to a nice separation of concerns.
You have detailed the disadvantages of this approach, however I think that the negative impact can be minimised with a reasonable caching strategy.
I'm not sure there's really much more I can contribute to this "question". I think you have a good understanding of the problems and solutions, advantages and disadvantages.
In the app I'm currently working on, we utilize a couple of these approaches by having both a base model object as well as a base controller. In order to minimize roundtrips, we store some data in session and re-populate in the model by overriding the OnActionExecuted in the base controller and grab the model out of the context and set properties out of session.
I'd certainly like to hear any wonderful solutions as well, but I think these are just the tradeoffs to deal with.

What's the overhead of including RenderPartial in an MVC3 page

I am trying to optimize my code as much as possible. I use a lot of partial files like this:
#if (Model.PageMeta.Sidebar == PageMetaSidebar.Small) { Html.RenderPartial("_SmallSidebar"); }
..
..
..
Can someone tell me if there is a performance overhead with this. I understand that Razor views are compiled. Is it the case that when the page is displays there is another disk read to get the data for each of the partial files that I use. If that's the case then how much additional overhead could I expect with for example 5 RenderPartials on my layout page.
There will be no noticable performance hit at all here as the partials are just pulled in on the asp.net web server before streaming the resultant HTML back to the browser. This is not an expensive disk read to do and won't appear any slower than if it was a single cshtml. Obviously partials should be used if the same partial view is reused in many views. If only used in a single view then it's just a matter of clarity splitting it into a separate partials to separate parts of your model into different views.
Note you can also just use:
#Html.Partial("YourPartial")
rather than using RenderPartial. This will look in the local view folder then in shared if not found.
I don't think using RenderPartial ~5 times is going to have a significant enough impact to design your pages poorly. If it makes sense to pull the logic out (makes the page cleaner, used by multiple views, etc.) then do it. If you notice significant performance issues then you should look at them at that time, but don't prematurely optimize and create a poor design because you THINK it might slow something down.
If you like to get a better understanding of potential performance hits you might want to play around with the mvc-mini-profiler.
Please note though that I'm not advocating pre-mature optimization. However, using profiling tools might give you a better understanding of potential bottlenecks, thus helping you avoid them in the future.

Asp.net MVC Pros and cons of composition DTOs vs strongly typed model+weakly typed ViewData passing?

I'm trying to find out what the issues are on each side of either composing a DTO that has the model+drop down lists,etc... vs passing those extra objects/lists in the ViewData. I haven't come up with an argument against using ViewData besides the strongly typed purist in me.
I thought I would ask what else I might need to consider?
It's a matter of encapsulation. I put everything I need to render the view (including dropdown list data and server-side validation) into the ViewModel object. That way I don't have stuff scattered to the high winds.
I'm not a purist, but the idea of pushing untyped information into the ViewData, and casting it to the correct type in the view, just feels uncomfortable to me. I have yet to find a situation where this makes sense, unless I am passing small bits of information to the view that have nothing to do with the ViewModel or the underlying database model.
Small bits of information that I would put in the ViewData might include things like paging links, or perhaps ReturnUrl references that I don't want to put in the Url as a parameter, nor do I want them polluting my ViewData object.
For testing purposes, it's better to keep most things in a custom ViewModel. You can more easily run proper tests on the data, - even without firing up the web server, so you win on performance as well.
Terje's point about testability is important. Also the performance point is obvious (no dictionary lookup or casting).
On the other hand, a weekly-typed ViewData mimics the Rails world. In the rare case where you have to translate a project from Rails to ASP.NET MVC in a very limited amount of time (which I actually had) this makes the process more direct. Which really cuts to the core of the one Pro for weakly-typed ViewData: rapid app dev.
Before I'm beat into oblivion with downvotes, I'm not advocating it as correct or proper. It's simply undeniable that using explicit ViewModels requires more dev resources to develop. What's saved in dev resources, is lost in performance, testability, and long-term maintainability.

Using partial views to simplify a complex view - a good approach?

Is it correct to use partial views for the SOLE purpose of breaking down a more complicated view into separate chunks and therefore making it more readable?
It probably seems a silly question but the reason I ask is that everything I've read about using partial views involves a piece of the UI being re-used in multiple places. In my case the piece of UI being put into the partial view is only used in one place. It is therefore done solely for readability, but I'm not sure if the performance impact of this may outweight the increased readability. Thoughts?
Whilst this is correct there are more uses.
Reusability
Ability to pass pack rendered html
from your controller so you can
append the partial view to the bottom
of containers. Great for jQuery
async calls
Seperation of concerns
Gives developers the ability to work
on different sections of a page w/out
getting in each others way.
Just to name a few.
I think that you shouldn't be worried about performance until it is a real problem, but you should be worried about your code from the first moment. I usually use partial views to simplify the logic or the structure of my views, as you are wanting to do.
Sure, that's an okay use for them. If it keeps the page organized so it's easier to maintain, I think it's fine.
Also, if I'm using caching, I find it easier to have my:
cache "this" do
# render partial
end
I find it easier to read and keep track of things, especially on an overview or dashboard page where there are lots of different parts of the pages that you're including.
I tend to be a bit more conservative. I only use a partial view when I know I'll need to reuse the code or I have multiple complex objects in ViewData that need to be displayed.
There's no right or wrong way here but I have worked on projects where there are a ton of partial views to make things "more simple" and I end up spending forever trying to track down where all the partials are (controller/action folder, shared folder, or elsewhere).
One thing about my approach though is if you have even the slightest thought that the view code may be reused down the line as the project changes use a partial. It will save a bunch of time down the road.
I veto any large and complex view in our projects. Instead, we use RenderAction to extract those pieces of code into smaller chunks/parts. I blogged about it here:
http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx
Basically, you move that logic and/or parts into Controllers.
Or, if you are just talking html - then yes, breaking down a view into RenderPartials works too.

Resources