简体   繁体   中英

ASP.NET MVC partial views slow?

I just happen to check the performance of an ASP.NET MVC application we are building. I was going to insert a partial view into a loop, and just out of curiosity I checked how long it took to render the page. The result was not good.

I need to do more conclusive investigation, but just in case there was somebody with similar issues or more insight, here is what I have so far. First, I should say that all results and measurements were done after multiple page loads and that I have set <compilation debug="false"> in my web.config.

  • It seems that a single render partial incurs about 5ms hit (at least in my environment). When I inline the actual content of the partial view, I get practically 0ms.
  • When I include an empty partial view to a loop of about 70 elements, the total render time increases by ~ 60ms. So there is some caching presumably, but it's not ideal.
  • I debugged ASP.NET MVC, and found out that partial views are cached, but it only caches the paths to the ascx's. The actual views are then instantiated every time using the BuildManager.CreateInstanceFromVirtualPath method.
  • And now the interesting bit: When include the same partial view using the WebForms syntax ( <my:UserContol runat="server" /> ), the extra 60ms go away.

So based on the observations above, it seems the culprit is the BuildManager.CreateInstanceFromVirtualPath method. Maybe, it was not meant to be called multiple times. Webforms presumably don't use it; or use it somehow only once for each ascx?

I've just changed a MVC2 view from using a partial view in a loop to a single view, ie :

<table>
foreach(var a in items)
{
  <%: Html.Partial("SomePartialView",a) %>
}
</table>

Where SomePartialView contains the code to render a single row in a table, eg :

<tr><td>Model.Name</td><td>Model.description</td></tr>

to :

foreach(var a in items)
{
  <tr><td>a.Name</td><td>a.description</td></tr>
}

for a view rendering 900 rows the page render time went down from 5+ minutes page load to less than 30 secs, pretty conclusive proof that there is a significant overhead when calling partial views. I'm sure this is negligible when you have a single call, however in a loop it all adds up so I'd recommended avoiding partial views in a loop if possible.

I am guessing the answer is ... it depends?

Partial views decrease performance (the overhead of the actual call etc).

Partial views are not cached.

Including a partial view inside a loop will decrease performance, and can be sped up again by moving the loop inside the partialview instead.

Some sample reading (which references the caching of the viewpath) can be found here .

60ms这么小的间隔对我来说听起来像统计噪音,而不是性能差异的确凿证据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM