Question

This is almost undoubtedly a dumb question. In my defence I'm ill. Anyway.

I've got an in memory list of objects. I've used the following expression to pull out the strings I'm interested in from my list of objects:

var myStrings = myListOfObjects.Select(r => r.MyString);

This provides me with an IEnumerable of string. myStrings will be reused a number of different times in my code later. What I'm wondering is, is there any performance benefit at all in performing a ToArray or ToList (ie a "greedy" operator) on this prior to making use of it? (So my operations would be directly against an Array / List.)

For what it's worth myStrings will be re-used in it's entirety when it is used.

Was it helpful?

Solution

It's a speed-space tradeoff.

If your Select() callback is computationally expensive, you probably want to computer it once and store it for later.

If not, you probably want to save on storage and compute it every time.

If you need random access, you should definitely call ToList(), because ElementAt() is O(n).

Note that ToList() is faster than ToArray(), because ToArray() needs to trim the array after it finishes.

OTHER TIPS

myStrings is just a query and not a collection. If you need it multiple times and it's not too large (for memory) you should better create a collection via ToArray or ToList.

Otherwise you're executing the query every time you access it(f.e. via foreach) due to it's deferred execution. This can also cause nasty bugs if the query now returns a different result.

Leaving it an IEnumerable would be the best unless you specifically need the List or Array functionality. No casting == fewer compute cycles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top