Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ new up memory when creating returns

Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?

like image 929
Joel B Avatar asked Jan 21 '11 17:01

Joel B


3 Answers

It's going to depend on if (and how) you use Select to project the results.

If you do not create new objects in a projection then the result will reference the same objects as the original collection.

If, however, you create new objects in the project then, obviously, they will not be the same.

The collection returned here will contain references to the same objects in _myCollection:

from m in _myCollection
where m.SomeFilterCriteria
select m

The collections returned in these cases will not:

from m in _myCollection
where m.SomeFilterCriteria
select new { m.Prop1, m.Prop2 }

In this case, it is worth pointing out that Prop1 and Prop2 of the new anonymous object - if they are reference types - will contain a reference to the same object as the original object. Only the top-level references in the collection will be different.

Basically - nothing in .Net aside from serializers (as mentioned elsewhere here) will "deep" copy, unless you implement it.

or

from m in _myCollection
where m.SomeFilterCriteria
select m.Clone()

Again, it would be a mistake to assume that any "deep" copying is going on here. Of course, Clone's implementation will be in the class and could be anything, including deep copying, but that is not given.

like image 50
quentin-starin Avatar answered Sep 25 '22 22:09

quentin-starin


Does LINQ actually perform a deep copy of the results to a different list/array/etc, or does it simply give me a list/array/etc. composed of references to the original?

From Enumerable.ToArray. (Similiar text found at Enumerable.ToList)

The ToArray(IEnumerable) method forces immediate query evaluation and returns an array that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.

Well, that certainly looks confusing.

  1. returns an array that contains the query results
  2. obtain a cached copy of the query results

From the first sentence, it is clear that no copies of items in the query are made.

From the second sentence, you get a copy of the query results as a whole, but that is a shallow copy since no copies of items in the query are made.

like image 43
Amy B Avatar answered Sep 26 '22 22:09

Amy B


What it returns is very dependent on which LINQ method you are referring to. But with the exception of the few methods which explicitly copy the enumeration (ToList and ToArray for example) the general pattern is to not copy the input to a new structure. Instead it prefers lazy evaluation.

like image 30
JaredPar Avatar answered Sep 24 '22 22:09

JaredPar