NateJ
NateJ

Reputation: 2005

Efficiency of List.Sort twice, vs. List.Clone & Sort

The language specifics: C# .NET 3.5/4.0; project is meant to be a pre-compiled DLL, a 'module' called/used by other products.

My question is about overall efficiency, and I realize this may come down to a "memory usage vs. CPU cycles" decision, which is fine -- I still want to know what you'd consider the better route.

I have a List of MyObjects passed into a method, and the method needs to Sort the List by Property2, do "some stuff" with it, then Sort the List by Property1 to do "something else" & continue with life. Important: the List is already ordered by Property1 when it first comes in to the method (say, from the data layer).

The Sorts will both be "custom inline", like so:

myList.Sort((ObjA, ObjB) => ObjA.Prop2.CompareTo(ObjB.Prop2));

Is doing the two Sorts a good idea? Or, would it be better to Clone the List to a new ListB, and only call Sort once (on ListB, by Prop2)? Then do "some stuff" with it, and when done, use original List for the "something else" & continue on.

My initial guess is that "Two Sorts" would spin more CPU cycles, whereas "Clone & Sort" would use more memory (since it has to create the new ListB object) -- and yes I know that the List members (MyObjects) would not be cloned, they'd just be pointed-at by the new ListB.

Thoughts?

Upvotes: 2

Views: 491

Answers (2)

Blindy
Blindy

Reputation: 67437

I'd process the output of myList.OrderBy(w=>w.Prop2) then I'd just use the original list since OrderBy isn't destructive.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564641

Making a new List<T> will be an O(n) operation, as each item will get copied into the new list. List<T>.Sort is typically O(n log n).

As such, sorting twice will be slower. Copying will require a copy of your list. It's a memory vs. speed trade off here.

That being said, copying won't change the sort order of the original list - this is a large advantage, in my opinion, as passing a list to a method and having it come back changed is often a source of bugs later, as people don't necessarily expect a method to mutate your ordering. This is especially true as your list is already sorted - if you went to the trouble of creating an ordered list, I would recommend avoiding changing that order if possible.

However, depending on what you're doing, you could just use Enumerable.OrderBy to pull out the second set in order, and do your "stuff". This also has the same advantage as the copy in that it doesn't change the ordering of the original list.

Upvotes: 7

Related Questions