这个例子中的 AsEnumerable 会提高效率吗?
Will AsEnumerable increase efficiency in this example?
在下面的代码中:
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);
数组已经是 Enumerable
。这不会有任何区别。
在下面的代码中:
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);
数组已经是 Enumerable
。这不会有任何区别。