Alena
Alena

Reputation: 179

Does duplicating lists lead to memory leaks?

Does this create memory leaks if used in cycles?

mylist = mylist.Distinct().ToList();

If so, whats a good approach for lists if you only need to update it(particularly with LINQ), not to create a new one?

Upvotes: 1

Views: 182

Answers (1)

Tim Long
Tim Long

Reputation: 13778

The cited line of code:

mylist = mylist.Distinct().ToList();

will create a new object of type List<T>, where T is typeof(mylist).

The list will contain references to a subset (possibly all, or none) of the original objects in mylist, as returned by the Distinct() LINQ operator.

Therefore, the situation you have after that line of code is that you have the original list, all of the original objects that were in the original list, plus a new list that references some subset of the original objects.

So yes, you've used a bit more memory (but not much, relatively speaking).

That in itself is not a memory leak. That would depend what you now do with your new list. If you simply set it to null, or it goes out of scope, then it will normally be garbage collected (eventually) and you'll get all the memory back; no leak. However, if you do something that causes another object to hold a reference to your list, then you could potentially have a memory leak.

Some ways that you could unknowingly be holding a reference to your new list include:

  • A lambda expression has 'closed over' the list variable and the lambda has been passed to another object. The list will then have the lifetime of the other object, even if it is out of lexical scope.
  • You've subscribed to an event on another object; the other object now holds a reference (via a delegate) to your object and it will be kept alive while the event subscription persists.
  • I'm sure there are others...

Upvotes: 1

Related Questions