Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22814

Performance implications of calling ToArray inside a LINQ selector

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.

Upvotes: 0

Views: 120

Answers (2)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47048

You can have a peek at the code for LINQBridge, especially the Select method (that ends up calling SelectYield.

The essence of SelectYield is a simple for-loop:

foreach (var item in source)
    yield return selector(item, i++);

Where selector is the lambda expression you pass in, in your case x => collection.ToArray()[index]. From here it is obvious that the whole lambda expression will be evaluated for every element in whatever.

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).

Upvotes: 0

cbp
cbp

Reputation: 25628

No, it will be performed once for every item in whatever.

Upvotes: 7

Related Questions