Which one has the best performance. I have a list array that contains a list of articles. When I list the articles I have a RenderPartial that displays just one article and the parent page goes through a loop of all the articles. The Renderpatial is inside the parentpage loop. What is the best way to go about this?
Loop inside the partial view if you can. Each time you call RenderPartial, the following things happen (courtesy of the MVC source files):
RenderPartial
callsRenderPartialInternal
RenderPartialInternal
creates a newViewDataDictionary
and a newViewContext
RenderPartialInternal
callsFindPartialView
to locate and instantiate a viewFindPartialView
searches all registered view engines (normally just one) for the view, using the controller context and view name as keys. Each view engine searches for the view in all the paths it supports, e.g. Views/controller/view.aspx, Views/controllers/view.ascx, Views/Shared/view.aspx, etc. Views can be returned from a memory cache to accelerate this stepThe view's
Render
method is called. I lost track of the inner workings of theRender
method of the standardWebFormView
at 13 levels down the stack.Render
constructs a large numbers of context objects the inner view needs, checks for permissions to run the view, hooks up events for any server controls, re-inspects the Request object to decide what more it needs to do, and so on. After actually rendering the view, it unwinds the context it has created.
Overall, none of these is too bad. It all happens inside the machine's CPU and RAM, which is more than can be said for typical database access that happens in the controller. The process needs to go out to disk only the first time the view is loaded (that can be slow, however; files have to be searched and the view has to be compiled). ASP.NET MVC had to optimize the view rendering process to maintain a high level of performance.
Still, this is quite a bit, and if you can avoid running it multiple times in one request, it will help improve the action method's response times.