Slow DisplayFor performance in ASP.NET Core MVC

In my current application, I am creating a rather long table to display to the user. I saw some serious performance issues that I was tracking before using @ Html.DisplayFor, and I'm not quite sure why.

Edit: I replaced the sample code with a more concise and reproducible setting.

To isolate the problem, I created a new MVC project with an asp.net database using all the default settings in visual studio without authentication. I created a view model as such:

public class TestingViewModel { public int Id { get; set; } public string TextValue1 { get; set; } public string TextValue2 { get; set; } } 

Then a controller is added that fills the view model with data to go to the view:

  public IActionResult TestThings() { var list = new List<TestingViewModel>(); for(var i = 0; i < 1000; i++) list.Add(new TestingViewModel {Id = i, TextValue1 = "Test", TextValue2 = "Test2"}); return View(list); } 

A view is the minimum minimum for displaying data:

 @model List<DisplayForTest.ViewModels.TestingViewModel> @foreach (var item in Model) { @Html.DisplayFor(m => item.Id) @Html.DisplayFor(m => item.TextValue1) @Html.DisplayFor(m => item.TextValue2) } 

It takes more than one second to run this code! The culprit is DisplayFor. If you change the view as follows:

 @model List<DisplayForTest.ViewModels.TestingViewModel> @foreach (var item in Model) { @item.Id @item.TextValue1 @item.TextValue2 } 

This is displayed in 13 ms. It is clear that DisplayFor adds a huge amount of time to render ... on my PC, which is about 0.4 ms per call. Although it is not bad in isolation, it makes it a pretty poor choice for lists or other things.

Is DisplayFor So Slow? Or am I using it incorrectly?

+5
source share
1 answer

Is DisplayFor Really So Slow? Or am I using it incorrectly?

Computing and executing lambda expressions requires a bit of overhead. The structure must first check it , then evaluate it . I'm thinking a bit here , but it seems like this is where performance issues come from; both of these methods require reflection.

All other display methods I've played with ( ValueFor , DisplayTextFor , etc.) have the same performance effect in your example.

I cannot talk to the MVC team about why it is used by default for scaffolding, but it makes sense to me. DisplayFor can handle both of the most common use cases (by displaying a property value and displaying a property value using a custom template), and in most cases performs fairly well.

In this case, I don't see a problem using only the raw value (basically .ToString ing) or using it in the Html.Encode / Html.Raw , depending on what you are looking for.

+2
source

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


All Articles