Performance 在这个例子中,一个可计算的值会提高效率吗?
在以下代码中:Performance 在这个例子中,一个可计算的值会提高效率吗?,performance,linq,Performance,Linq,在以下代码中: private bool IsValid() { return new[] { User.GetProfileAttributeByName("1"), User.GetProfileAttributeByName("2"), User.GetProfileAttributeByName("3"), User.GetProfileAtt
private bool IsValid()
{
return new[]
{
User.GetProfileAttributeByName("1"),
User.GetProfileAttributeByName("2"),
User.GetProfileAttributeByName("3"),
User.GetProfileAttributeByName("4")
}.All(c => c != null);
}
我认为数组已经完全物化了,调用了User.GetProfileAttributeByName
4次,然后在第一次遇到null
时所有的电路都短路了
请注意:
private bool IsValid()
{
return new[]
{
User.GetProfileAttributeByName("1"),
User.GetProfileAttributeByName("2"),
User.GetProfileAttributeByName("3"),
User.GetProfileAttributeByName("4")
}.AsEnumerable().All(c => c != null);
}
使All
一次计算一个元素,还是数组仍将首先完全物化
(我意识到如果我只使用&&和一个普通表达式,这是没有意义的-我只是想完全理解这个示例)这不会有任何区别-数组初始化不会被延迟计算,而使用
AsEnumerable
不会改变这一点
您可以通过将查询更改为:
return new[]
{
"1",
"2",
"3",
"4"
}.Select(s => User.GetProfileAttributeByName(s))
.All(c => c != null);
然后,Select
将被延迟评估,并且All
将短路
或者只是
return new[]
{
"1",
"2",
"3",
"4"
}.All(s => User.GetProfileAttributeByName(s) != null);
这不会有任何区别-数组初始化不会被延迟计算,使用
AsEnumerable
不会改变这一点
您可以通过将查询更改为:
return new[]
{
"1",
"2",
"3",
"4"
}.Select(s => User.GetProfileAttributeByName(s))
.All(c => c != null);
然后,Select
将被延迟评估,并且All
将短路
或者只是
return new[]
{
"1",
"2",
"3",
"4"
}.All(s => User.GetProfileAttributeByName(s) != null);
该数组已经是可枚举的。这不会有任何区别。数组已经是可枚举的。这不会有任何区别。您也可以使用
Lazy
,它基本上就是为了这个目的而存在的。您甚至可以在Select上将其缩减为一个方法组(即“方法组”)正确的术语是什么?我想我是从一些东西中推断出来的,但我不是肯定的,我是对的……是的-你可以将投影和空检查结合起来。我已经在我的答案中添加了这一点。你也可以使用惰性,它几乎就是为了这个目的而存在的。你甚至可以在Select上把它缩减为一个方法组(即“方法组”)正确的术语是什么?我想我是从某种东西上推断出来的,但我不是肯定的,我是对的……是的,你可以把投影和空检查结合起来。我已经把它添加到我的答案中了。