Operating costs for using Partials in Razor view

I like the partial parts in Razor views. This makes the code nice and clean. But is there a significant cost to using partial data? I created a simple test. He shows that using partial contractions 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 partial execution code is 340 ms, and the inline @str code is 0 or 1 ms. It really shockes me, because it means that I have to get rid of all my pretty particles, at least those in cycles.

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

+6
source share
3 answers
  • Make sure that you do not start your site in debug mode and that the MVC project is compiled in the release configuration. Running a site in debug mode makes MVC skip a bunch of caching
  • You have not provided your base code, so it is difficult to determine if your conclusions are justified.
  • Do you think 1000 calls are distributed to Partial? It looks like you are measuring a scenario that is not realistic. On any rather complex website, the cost of database calls will usually outshine any of the lookup codes.
  • Watch this video: http://channel9.msdn.com/Series/mvcConf/mvcConf-2-Steven-Smith-Improving-ASPNET-MVC-Application-Performance
+7
source

In this operation, you have a stopwatch going through the cycle 1000 times, and access to this partial. This partial is located in a separate memory location and may even require disk I / O access to boot. This is clearly inferior to the position of this code on the page itself.

But do not reject particulars everywhere. If you are in a situation where you do not have the code that was downloaded several times on the page (unlike the code that you showed), then partial files are very useful, and the penalty for the execution that they put is not so serious that you should be worried.

+2
source

Yes, using particulars leads to a penalty for productivity; you need to open and read a new file, and IO is always slow / expensive.

-2
source

Source: https://habr.com/ru/post/886357/


All Articles