sne*_*rch 6 c# performance foreach linq-to-objects coding-style
我有一段代码用于某些验证逻辑,其概括如下:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection)
{
foreach(var foo in collection)
{
Target target = SomeFancyLookup(foo);
if (!target.Satisfactory)
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
这很有效,很容易理解,并且具有早期优化功能.然而,它非常冗长.这个问题的主要目的是什么被认为是可读和良好的风格.我也对表演很感兴趣; 我坚信过早的{优化,悲观化}是万恶之源,并试图避免微观优化以及引入瓶颈.
我对LINQ很新,所以我想对我提出的两个替代版本以及其他任何建议进行评论.可读性.
private bool AllItemsAreSatisfactoryV2(IEnumerable<Source> collection)
{
return null ==
(from foo in collection
where !(SomeFancyLookup(foo).Satisfactory)
select foo).First();
}
private bool AllItemsAreSatisfactoryV3(IEnumerable<Source> collection)
{
return !collection.Any(foo => !SomeFancyLookup(foo).Satisfactory);
}
Run Code Online (Sandbox Code Playgroud)
我不相信V2在可读性方面提供了超过V1,即使更短.我发现V3清晰简洁,但我不太喜欢这个Method().Property部分; 当然,我可以把lambda变成一个完整的代表,然后它失去了它的一线优雅.
我想评论的是:
提前致谢 :)
Lee*_*Lee 13
我认为All会更清楚:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection)
{
return collection.Select(f => SomeFancyLookup(f)).All(t => t.Satisfactory);
}
Run Code Online (Sandbox Code Playgroud)
我认为在这里使用linq不太可能在常规的foreach循环中引起性能问题,尽管如果改变它会直接改变.