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.
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(), becauseElementAt()is O(n).Note that
ToList()is faster thanToArray(), becauseToArray()needs to trim the array after it finishes.