Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impact of IEnumerable.ToList()

Tags:

c#

I'm just wondering what goes on when calling .ToList() on an IEnumerable in C#. Do the items actually get copied to completely new duplicated items on the heap or does the new List simply refer to the original items on the heap?

I'm wondering because someone told me it's expensive to call ToList, whereas if it's simply about assigning existing objects to a new list, that's a lightweight call.

I've written this fiddle https://dotnetfiddle.net/s7xIc2 Is simply checking the hashcode enough to know?

like image 228
Stephen York Avatar asked Dec 14 '22 13:12

Stephen York


1 Answers

IEnumerable doesn't have to contain a list of anything. It can (and often does) resolve each current item at the time it is requested.

On the other hand, an IList is a complete in-memory copy of all the items.

So the answer is... It depends. What is backing your IEnumerable? If its the file system then yes, calling .ToList can be quite expensive. If its an in-memory list already, then no, calling .ToList would not be terribly expensive.

As an example, lets say you created an IEnumerable that generated and returned a random number each time .Next was called. In this case calling .ToList on the IEnumerable would never return, and would eventually throw an Out Of Memory exception.

However, an IEnumerable of database objects has a finite bounds (usually :) ) and as long as all the data fits in memory, calling .ToList could be entirely appropriate.

like image 51
Sam Axe Avatar answered Dec 26 '22 22:12

Sam Axe