c# - 循环中的实例化 : Verbosity vs. 性能

标签 c# performance

所以在下面的代码中,我真的很喜欢场景一的冗长,但我想知道与场景二相比,这对性能有多大影响。循环中的实例化很重要吗?

语法上的好处(我喜欢,有些人甚至可能不同意它是冗长的或最佳的)是否值得所说的性能损失?您可以假设集合仍然相当小(N < 几百)。

// First scenario
var productCategoryModels = new List<ProductCategoryModel>();
foreach (var productCategory in productCategories)
{
    var model = new ProductCategoryModel.ProductCategoryModelConverter(currentContext).Convert(productCategory);
    productCategoryModels.Add(model);
}

// Second scenario
var productCategoryModels = new List<ProductCategoryModel>();
var modelConvert = new ProductCategoryModel.ProductCategoryModelConverter(currentContext);

foreach (var productCategory in productCategories)
{
    var model = modelConvert.Convert(productCategory);
    productCategoryModels.Add(model);
}

很想听听你们对此的看法,因为我经常看到这种情况。

最佳答案

我会以不同的方式处理这个问题。如果 new ProductCategoryModel.ProductCategoryModelConverter(currentContext) 中发生的任何事情在循环期间都没有改变,我认为没有理由将它包含在循环中。如果它不是循环的一部分,那么它不应该在 imo 中。

如果仅仅因为它看起来更好而将其包括在内,就会迫使读者弄清楚它是否有所作为。

关于c# - 循环中的实例化 : Verbosity vs. 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3234605/

相关文章:

c# - 在选择更改事件上禁用事件冒泡 - WPF

performance - Excel:使用外部链接可以提高性能吗?

c# - StreamReader 和 StreamWriter 的性能问题

java - 在 Java 中测量单线程复杂算法的最佳宏基准测试工具/框架是什么?

c++ - 英特尔编译器生成的代码比 MSVC 慢 68%(提供了完整示例)

c# - Active Directory RoleProvider -Principal.IsMemberOf 抛出PrincipalOperationException

c# - 在 C# 中将 XML 反序列化为类 obj

c# - 关于 NullReferenceException 的困惑

c# - 为什么 C# 编译器无法检测到 this 不能为 null?

java - Perf4j 未正确记录