What's the overhead of including RenderPartial in an MVC3 page - asp.net-mvc

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.

Related

RenderAction vs RenderPartial performance

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.

Are there any performance gains by moving logic from the view to the viewmodel?

Obviously there is lot's to gain by moving structure and logic into a viewmodel. How much is perhaps a matter of taste.
One big plus for the developer of keeping logic in cshtml is you don't have to recompile the whole project.
But are there any performance gains for the user to consider?
Clarfication
My viewmodels contain logic for example replacing \n with and returning HtmlStrings, combining booleans, comparing UTC-dates. But no foreaching of comments, since there is structure in there, albeit very little.
Depending on the logic the main benefit would be to the user and how fast the page displays.
Theoretically MVC shouldn't have any logic in the view, but we all know that on a pragmatic approach there may be some in order to expedite certain functionality in the View.
What is annoying though is when developers embed, large scripts in the View, which can really hamper the user experience especially over a slow connection.
On the whole though the biggest bugbear for web page performance is data access. A decent data cacheing process will have a vast effect on performance, as it cuts down all of those database queries.

Partial controls in Asp.net mvc page

At my new job, I was given some MVC work. There is only one controller with nine action methods(6 are for ajax rendering) . The page was bit large, so I divided it into small your controls and used render partial to render them. Some user controls were being render through ajax also. Most of the controls are not more like foreach loops and rendering some data from tables, not more 10-15 lines. The main index page passes model to all the controls. My main page looked very clean and easy to maintain.
But my team members are saying, I should put everything in the main page rather than building small controls. Their point is number of files will be a lot, if we start creating controls like this. Also they say if we are not reusing these controls somewhere else there is no point creating them separately.
I would like to know what is better approach for this kind of scenario. Any good links which can help us to understand things better, or any book we can read to clarify our questions.
Help will be appreciated.
Regards
Parminder
As a preface to my answer, let me mention the important value of maintainability. Software evolves over time... and must change to fit the need of the application.
Maintainability in code does not magically appear... Sacrifices (with a touch of paranoia sometimes) must be made in your coding style now, to have the flexibility you'd like in the future.
There may a large page in your project. Some may say that if it works, no need to fix it. But that's looking at it from a short term perspective. You may need some of those UI interfaces in other places in the future. What some persons may do (rather than make partials) is copy that code in the places where they need it - thus causing the same bloat over time that they were trying to avoid.
If you're on the project in the long haul, you'll more fully appreciate the need for flexibility over time. You can see that there are patterns that you'll want to re-use.
My suggestion then: Partials and controls are good things... they are good investments for your ease in the future. If you forecast reusability, that's a good sign for using them.
But use them sparingly. Don't micromanage everything on a page. Some things may be itching to be 'component-ized' but sometimes it's best to SSFL (Save some for later). Like everything in life, balance is important.
Having clean concise code is the way to go. Your code will be alot more readable if you utilize :
sections
templates
partial views
Just remember its always easier to navigate folder structure than to read 100's - 1000's of lines of code.
I recommend watching "Putting your controllers on a diet" by Jimmy Bogard.
Also read "Fat Controllers" by Ian Cooper.
these two links will give you a good idea on how to structure your MVC apps.

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.

Is calling a partial an expensive operation?

Can I use partials as much as I want or do I have to restrain myself to avoid bringing my views to a crawl under much traffic?
There's an obvious overhead using partial but this isn't something you should probably worry about.
Partials are files. When you render an action without partials, your action "costs" 1 file (that's not totally true, but this is to simplify the explanation).
If your action renders 4 partials, you end up with a cost of 5. This means, you have 4 additional IO calls and the real cost for each call depends on your server load, server performances and so on.
But does this cost matter? In my experience, for the 99% of times no. Also noteworthy, the benefits of using partials in terms of code readability and maintainability usually are worth the choice.
If performances must be a key feature, you should probably look for speed and improvements elsewhere.
Remember: Ruby is not a super-fast programming language and code expressiveness always took the first place in favor of performances. Rails implicitly agree to this convention, albeit the Rails team has always focused on performances (and Rails 3 it's the practical demonstration there's always place for improvements)
That said, you can safely use partials and reduce the application overhead with some clever caching mechanism. For example, you can place collection rendering within a cache block so that a render collection statement will be executed only once then your app will simply load 1 cache file instead of 10 un-cached partials.
One of the most sneak errors I made many times at the beginning was to worry about performances in the wrong way, that said, without actually running benchmarks. I remember once when I was trying to drop one single database query in favor of an hard coded hash because "the query costs", without realizing there was an other stupid query that was loading an entire table collection without the include statement, that resulted in running the second query 3 times slower.
So, if you really care about performance, you probably shouldn't avoid using partials but instead make sure you are taking advantage of all the other features Rails provides you to scale your application.

Resources