Evgenii
Evgenii

Reputation: 37339

Performance cost of using Partials in Razor views

I like using partials in my Razor views. It makes the code nice and clean. But is there any significant performance cost of using partials? I've created a simple test. It shows that using partials is much slower.

test.cshtml:

@{
   var stopwatch = new System.Diagnostics.Stopwatch(); 
   stopwatch.Start();         
   for(var i=0; i<1000; i++) {
      var str = "my string #" + i;        
      @Html.Partial("_MyPartial",str)  // replace with @str on second test
      <br />        
   }
   stopwatch.Stop();
   <br />
   @: Time elapsed (ms): @(stopwatch.ElapsedMilliseconds)
}

_MyPartial.cshtml:

@Model

The code with the partial executed in 340ms, while the inline @str code was showing 0 or 1 ms. It is really shocking for me because it means I should get rid of all my cute partials, at least of those in loops.

If anyone wants to confirm or criticize my experiment, you are very welcome.

Upvotes: 11

Views: 5491

Answers (3)

marcind
marcind

Reputation: 53183

  1. Make sure you are not running your site in debug mode and that the MVC project is getting compiled in the release configuration. Running a site in debug mode makes MVC skip a bunch of caching
  2. You did not provide your baseline code so it's hard to determine if your conclusions are justified.
  3. Do you think that having a 1000 calls to Partial is common? Seems like you are measuring a scenario that's not realistic. In any reasonably complex website the cost of database calls will usually dwarf any of the view code.
  4. Please watch this video: http://channel9.msdn.com/Series/mvcConf/mvcConf-2-Steven-Smith-Improving-ASPNET-MVC-Application-Performance

Upvotes: 10

Cyril Gupta
Cyril Gupta

Reputation: 13723

In this operation you've got a stopwatch that's going through a loop 1000 times, and accessing that partial. That partial is in a separate memory location, and may even require disk i/o access to load. It's clearly inferior to putting that code on the page itself.

But don't reject the partials everywhere. If you are in a situation where you don't have code that's loaded multiple times on the page (unlike this code you've showed), then partials are pretty useful, and the performance penalty they inflict isn't so severe that you should be troubled.

Upvotes: 2

Esteban Araya
Esteban Araya

Reputation: 29664

Yes, using partials does inflict a performance penalty; a new file has to be opened and read, and IO is always slow/expensive.

Upvotes: -2

Related Questions