1367 Views
The IEnumerable(T) extension methods ToList and ToArray are commonly used at boundaries to prevent a potential performance impact from consumers iterating a sequence more than once. This is due to the lazy evaluation strategy used by the LINQ extension methods to IEnumerable(T) which provides better performance as you are constructing your query since each modification to the query is not forcing the sequence to be iterated. However, are these two methods used correctly?
My argument is as follows :
Assuming your intent is to materialize a sequence and you are using ToList for the implication that the sequence will be materialized.
Using a Materialize method instead:
1) makes your intent clear
2) prevents misinterpretation due to other implications
3) provides one location to change the implementation details for materializing a sequence
Please note this is different than a Memoize function, which isn't as eager. Memoize would cache the results upon evaluation so subsequent traversal will not cause evaluation.