在 LINQ 选择器内调用 ToArray 的性能影响
如果我有以下语句:
whatever.Select(x => collection.ToArray()[index]).ToList();
LINQ 是否足够智能,可以仅执行一次 ToArray
转换(我不太清楚这个闭包是如何转换和评估的)?
我明白这段代码不好,只是感兴趣。
If I have the following statement:
whatever.Select(x => collection.ToArray()[index]).ToList();
Is LINQ smart enough to perform the ToArray
cast only once (I'm not really aware of how this closure is transformed and evaluated)?
I understand that this code is bad, just interested.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它会对 whatever 中的每个项目执行一次。
No, it will be performed once for every item in whatever.
您可以查看 LINQBridge 的代码,尤其是
Select
方法(最终调用SelectYield
SelectYield
的本质是一个简单的 for 循环:其中
selector
是您传入的 lambda 表达式,在您的例子中x = ()[index]
。从这里可以明显看出,将为whatever
中的每个元素计算整个 lambda 表达式。请注意,LINQBridge 是 LINQ2Objects 的独立重新实现,因此不一定。相同(但在很大程度上至少表现得与 LINQ2Objects 完全相同,包括副作用)。
You can have a peek at the code for LINQBridge, especially the
Select
method (that ends up callingSelectYield
.The essence of
SelectYield
is a simple for-loop:Where
selector
is the lambda expression you pass in, in your casex => collection.ToArray()[index]
. From here it is obvious that the whole lambda expression will be evaluated for every element inwhatever
.Note that LINQBridge is a stand alone reimplementation of LINQ2Objects and thus not necessarily identical (but to a very large extent at least behaving exactly like LINQ2Objects, including side effects).