背景:我的游戏使用的是组件系统。我有一个 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
循环所做的。因此,请使用 First
或 FirstOrDefault
而不是 Single
。
关于c# - Linq 单次调用缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677151/