c# - Linq 查询中的匿名类型与元组,性能注意事项

标签 c# linq tuples anonymous-types

这个问题专门针对内存数据,与查询翻译框架无关(例如,与 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

我们的业务规则类似于:

  • 如果 ExemplarFriendNames 包含的条目未显示为另一个 ExemplarName,则该 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.

主要差异

<表类=“s-表”> <标题> 姓名 访问修饰符 类型 自定义名称 解构 表达式树 <正文> 匿名类型 内部 类 ✔️ ❌ ✔️ 元组 公开 类 ❌ ❌ ✔️ 值元组 公开 结构 ✔️ ✔️ ❌

性能

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/

相关文章:

c# - 如何调用 delete/put 方法以从 silverlight 中恢复服务

c# - Linq to XML 返回 Null

c# - 字符串数组到字符串转换所需的 Linq 语法

python - 如何加入两个没有重复的元组列表

python - 如何返回 endswith 函数中匹配的元组中的哪个元素

c++ - 制作自定义类型 "tie-able"(与 std::tie 兼容)

c# - AutoMapper 更改类型

c# - 如何在 WPF 中处理 WndProc 消息?

c# - 如何从 LINQ to SQL 中的另一个项目获取连接字符串?

c# - ComboBox.SelectedValue 抛出空引用异常