Does IEnumerable save storage objects after use

If I have a very large collection of IEnumerable , in the order of millions of objects, that would be too large to load everything at once. Collections are returned by the yield method:

  private static IEnumerable<MyData> ExtractModelsFromDb() { using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Load MyData yield return MyData; } reader.Close(); } } 

This data is consumed in one Foreach cycle:

 public void RunStuff() { var myCollection = ExtractModelsFromDb(); foreach (var data in myCollection) { //DO STUFF } } 

I know that a collection under IEnumerable loaded one object at a time, but objects are deleted after they are used in Foreach or they remain in the collection until Foreach complete.

+4
source share
1 answer

It depends on the implementation. This is consistent with the IEnumerable specification for storing values ​​in the sequence that it represents. In fact, a List<T> is an IEnumerable<T> that does just that!

Now for the IEnumerable that you have, it will not save the objects after they are returned. DbDataReader just pass the results to you, and yield return will not save them. That way, your foreach just flows over the result set from DbDataReader , and no one saves them, as you carefully navigate the stream .

+4
source

Source: https://habr.com/ru/post/1493553/


All Articles