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.
Partial views are an effective way to: Break up large markup files into smaller components. In a large, complex markup file composed of several logical pieces, there's an advantage to working with each piece isolated into a partial view.
RenderPartial function to render Partial View in ASP.Net MVC Razor. The data will be fetched from database using Entity Framework and then the Partial View will be rendered using the @Html. RenderPartial function in ASP.Net MVC Razor.
A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.
View components are similar to partial views, but they're much more powerful. View components don't use model binding, and only depend on the data provided when calling into it. This article was written using controllers and views, but view components also work with Razor Pages.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With