List.OfType<> 的性能影响是什么?整个列表在哪里是该类型?

发布于 2024-12-01 05:20:18 字数 573 浏览 5 评论 0 原文

我有一个架构,我们将数据节点作为 IEnumerable 传递。一切都很好,但在每个子类中,我们希望将它们存储为 List ,因为该类中的所有内容都会创建并使用 AnotherNode 对象(我们大约有 15 个不同的子类) )。

使用更强类型列表不起作用的地方是根类方法,该方法返回类型 IEnumerable 并且由于 .net 3.5 中的协方差限制,无法返回该类型。 (我们现在必须保留在 .net 3.5 上。)

但是如果我有 List data; 并返回 data.OfType(); - 效果很好。这是我的问题。

由于所有数据都是 BaseNode 类型 - 此调用对性能有何影响?因为另一种选择是我必须在性能受到较小影响的地方进行投射 - 但这也是我们放弃一切知道其类型的情况。

I have an architecture where we are passing our data nodes as IEnumerable<BaseNode>. It all works great, but in each subclass we want to store these as List<AnotherNode> as everything in that class creates and uses AnotherNode objects (we have about 15 different subclasses).

The one place using the more strongly typed list doesn't work is the root classes method that returns a type IEnumerable<BaseNode> and with the covariance limitations in .net 3.5, that can't be returned. (We have to stay on .net 3.5 for now.)

But if I have List<AnotherNode> data; and return data.OfType<BaseNode>(); - that works fine. So here's my question.

As all of data is of type BaseNode - what's the performance hit of this call? Because the alternative is I have to cast in places which has a small performance hit - but it's also a situation where we give up everything knowing it's type.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

滥情稳全场 2024-12-08 05:20:18

两件小事:

  1. 与生成枚举器中的每个项目相关的开销虽小,但可测量。如果您因为处于非常紧密的内部循环中而需要关心这一点,那么实际上最好直接在列表上使用 for 循环进行迭代。这很可能并不重要。

  2. 由于结果是 IEnumerable 并且已通过生成枚举函数​​进行过滤,因此对 Count() 或 ElementAt() 等方法的后续调用将不会利用 LINQ 中的优化列表的实现。这也不太可能成为问题,除非您经常使用这些扩展方法并且拥有大量元素。

Two minor things:

  1. There is a small, but measurable overhead associated with yielding each item in the enumerator. If you need to care about this because you're in a very tight inner loop, you're actually better off iterating with a for loop on the list directly. Most likely this doesn't matter.

  2. Because the result is IEnumerable<BaseNode> and has already been filtered through a yielding enumeration function, subsequent calls to methods like Count() or ElementAt() will not take advantage of optimizations in the LINQ implementation for Lists. This is also unlikely to be a problem unless you make frequent use of these extension methods and have a very large number of elements.

ヤ经典坏疍 2024-12-08 05:20:18

您见过 Cast() Linq 运算符吗?它应该比 OfType() 性能更高。

基本上有一个使用 OfType() 运行的条件,

if (item is T) {
    yield return (T)item;
}

将其与 Cast() 的作用进行对比:

yield return (T)item;

Have you seen the Cast<T>() Linq operator? It should be more performant than OfType<T>().

Basically there is a condition that is run with OfType<T>()

if (item is T) {
    yield return (T)item;
}

Contrast that with what Cast<T>() does:

yield return (T)item;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文