这个问题专门针对内存数据,与查询翻译框架无关(例如,与 Entity Framework 以及它如何能够和不能转录某些 Linq 查询无关)。
假设我们有一个 IEnumerable
包含类型:
class Exemplar
{
public Guid UniqueId { get; set; }
public string Name { get; set; }
public string[] FriendNames { get; set; }
}
var exampleData = new List<Exemplar>(); // pretend I'm populated
我们的业务规则类似于:
- 如果
Exemplar
的FriendNames
包含的条目未显示为另一个Exemplar
的Name
,则该Exemplar
无效> 在我们的exampleData
中
- 如果发现无效的
Exemplar
,请写出其UniqueId
及其无效的FriendNames
我习惯于编写使用匿名类型作为链中中间结构的 Linq 查询。例如:
var invalidExemplars =
exampleData
.Select(x =>
new
{
Id = x.UniqueId,
InvalidNames = x.FriendNames.Where(n => exampleData.All(d => d.Name != n)).ToArray()
})
.Where(x => x.InvalidNames.Any());
// added for completion, maybe irrelevant to the question
if (invalidExemplars.Any())
{
Console.WriteLine(string.Join(Environment.NewLine, invalidExemplars.Select(x => $"{x.Id}: [{ string.Join(",", x.InvalidNames)}]")));
}
但现在使用 C# 7,我们可以使用新的元组简写来代替匿名类型:
var invalidExemplars =
exampleData
.Select(x =>
(
Id: x.UniqueId,
InvalidNames: x.FriendNames.Where(n => exampleData.All(d => d.Name != n)).ToArray()
))
.Where(x => x.InvalidNames.Any());
我的问题是中间匿名类型与中间元组之间是否存在性能差异,如果有的话,它们是什么?
是否有任何理由(除了个人偏好之外)选择其中一个作为中介??
最佳答案
匿名类型和值元组之间存在一些非常微妙的差异。
- 平等
- 存储 - 堆/堆栈
- 参数命名
- 表达式树
- 语法 - 构造语法、解构语法等
- 用法 - 如何将它们用作方法参数等
由于这个问题是关于中间体使用的,值元组可能会因为LINQ、表达式树和而被分配堆。 >ORMS 不在等式之内。那么除了相等和语法之外,几乎没有什么区别,此外,性能影响将相当不明显。所以答案实际上归结为选择你最喜欢的。
其他资源
Choosing between anonymous and tuple types
权衡
You might want to always use ValueTuple over Tuple, and anonymous types, but there are tradeoffs you should consider. The ValueTuple types are mutable, whereas Tuple are read-only. Anonymous types can be used in expression trees, while tuples cannot. The following table is an overview of some of the key differences.
主要差异
性能
Performance between these types depends on the scenario. The major impact involves the tradeoff between allocations and copying. In most scenarios, the impact is small. When major impacts could arise, measurements should be taken to inform the decision.
进一步阅读
关于c# - Linq 查询中的匿名类型与元组,性能注意事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308475/