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?