在我当前的应用程序中,我生成了一个相当长的表格来显示给用户。我发现它存在一些严重的性能问题,我已将其归因于 @Html.DisplayFor 的使用,但我不完全确定原因。
编辑:我用更简洁和可重现的设置替换了代码示例。
为了隔离问题,我在 visual studio 中使用所有默认设置创建了一个新的 asp.net core MVC 项目,没有身份验证。我这样创建了一个 View 模型:
public class TestingViewModel
{
public int Id { get; set; }
public string TextValue1 { get; set; }
public string TextValue2 { get; set; }
}
然后添加一个 Controller ,用数据填充 View 模型以传递给 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);
}
View 是显示数据的最低限度:
@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)
}
运行此代码时,需要超过一秒钟的时间才能运行!罪魁祸首是 DisplayFor。如果我按如下方式更改 View :
@model List<DisplayForTest.ViewModels.TestingViewModel>
@foreach (var item in Model)
{
@item.Id
@item.TextValue1
@item.TextValue2
}
这会在 13 毫秒内呈现。很明显,DisplayFor 增加了大量的渲染时间……在我的 PC 上,每次调用将近 0.4 毫秒。虽然单独来看这还不错,但对于列表或其他东西来说,它是一个非常糟糕的选择。
DisplayFor
真的有那么慢吗?还是我使用不当?
最佳答案
Is DisplayFor really just that slow? Or am I using it incorrectly?
评估和执行 lambda 表达式需要一些开销。首先,框架必须 validate it , 然后 evaluate it . 我在这里做了一些推测,但似乎这就是性能问题的来源;这两种方法都需要反射(reflection)。
我使用过的所有其他显示方法(ValueFor
、DisplayTextFor
等)在您的示例中都具有相同的性能效果。
我不能代表 MVC 团队说明为什么将它用于默认脚手架,但它对我来说确实有意义。 DisplayFor
可以处理两种最常见的用例(显示属性的值,以及使用自定义模板显示属性的值),并且在大多数情况下表现相当不错。
在这种情况下,我没有看到仅使用原始值(基本上是 .ToString
ing)或在 Html.Encode
中使用它的问题/Html.Raw
方法取决于您要查找的内容。
关于c# - 缓慢显示对于 ASP.NET Core MVC 中的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028594/