c# - Linq 单次调用缓慢

标签 c# linq optimization

背景:我的游戏使用的是组件系​​统。我有一个 Entity具有 IComponent 列表的类List<IComponent> 中的实例.我当前执行的 Entity.GetComponent<T>()是:

return (T)this.components.Single(c => c is T);

添加碰撞检测后,我注意到我的游戏下降到 1FPS。分析显示罪魁祸首就是这个调用(每帧调用 3000 多次)。

除了 3000x,我注意到调用这个 300k 次大约需要 2 秒。我将它优化为一个简单的迭代循环:

foreach (IComponent c in this.components) { 
  if (c is T) {
    return (T)c; 
  }
}

return default(T);

这段代码现在运行时间大约为 0.4 秒,好一个数量级。

我以为Single会比单个 foreach 循环更有效。这是怎么回事?

最佳答案

Single 的文档说:

Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

另一方面First:

The first element in the sequence that passes the test in the specified predicate function.

因此,使用 Single,您可以遍历整个序列而无需短路,这就是上面的 foreach 循环所做的。因此,请使用 FirstFirstOrDefault 而不是 Single

关于c# - Linq 单次调用缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677151/

相关文章:

c# - 在 C#/.NET 中模拟没有无参数构造函数的对象

c# - 时间表 : Retrieve data using SQL, LINQ 或类?

c# - 动态 Linq 查询未按预期工作 - 我做错了什么?

mysql - 优化 MySQL 查询以避免 “Using temporary” 和 “Using filesort”

c# - 是否已经内置了像这样的功能性 C#/.NET 结构? g(h()), 或

c# - 在 FlipView 的 KeyDown 事件中处理方向键

javascript - 在 Javascript 中轻松添加值数组(例如,没有循环)

Javascript FF 慢速 Chrome/Safari 快速

c# - 我应该使用哪种 MySql InnoDB 事务隔离级别?

c# - .NET CORE 2 EF 包含