Reputation: 37339
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
Reputation: 53183
Upvotes: 10
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
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