2

on C# list ordering I found this old debate on stack overflow: How to Sort a List<T> by a property in the object

I myself used to order lists the same as the most voted reply in above link:

List<Order> newList = oldList.OrderBy(o=>o.SomeProperty).ToList();

not thinking that this creates a whole new list in the memory. Hence the second most voted reply in above link offers itself as the best solution (.Sort with Comparison).

My question is, if changing the first solution will avoid memory duplication:

oldList = oldList.OrderBy(o=>o.SomeProperty).ToList();

or does this again create a new list in memory?

note:I tested already and ordering works this way, but I don't know how to check for (extra/new) memory usage.

Thank you M

TheMixy
  • 1,049
  • 15
  • 36
  • 3
    you modified version **will** create another list in memory, but as you assign this new list to the same variable, unsorted list probably will be disposed by GC (if there is no another variable pointing to unsorted list) – vasily.sib Sep 20 '18 at 11:44
  • 1
    My opinion: if your list has 100 Million items, then it's probably too big to start with, and you need to revisit your design. If your list has 10 items, then it's not really a problem and you are trying to fix a problem that doesn't exist. – Neil Sep 20 '18 at 11:49
  • [`GC.GetTotalMemory`](https://stackoverflow.com/questions/750574/how-to-get-memory-available-or-used-in-c-sharp). If you look at the [source code](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,e449fbc07f49dc52), `OrderBy` also makes temporary buffer array with the keys to sort by. – Slai Sep 20 '18 at 12:27

1 Answers1

2
oldList = oldList.OrderBy(o=>o.SomeProperty).ToList();

Will create a new list in memory and assign the reference oldList to it. You will have two lists in memory, one sorted and one unsorted. The unsorted list will live on in the memory until there are no other remaining references to it. At that point the list is viable for garbage collection and the memory will eventually be freed or reclaimed.

Okami
  • 120
  • 1
  • 6
  • 3
    Slight inaccuracy in your answer: The GC will not necessarily run/collect the original list at the point where there are no references to the list anymore. Of course, no path of refrences from locals/static/pinned objects down to the original list object is a requirement for it to be collected, but the time when the GC actually runs is independent from that and depends on other conditions (such as memory pressure, for example) –  Sep 20 '18 at 11:53
  • 1
    @elgonzo is right, do not rely on GC. There is no guarantee that it will ever collect this list. – vasily.sib Sep 20 '18 at 11:56
  • You are correct and I have updated my answer to reflect this. Thank you for pointing it out! – Okami Sep 20 '18 at 12:00