Does sorting value types create copies?

python sorted
python sort list of lists
sort vs sorted python
python sorted lambda
python sort vs sorted performance
python sorted key=lambda
python sorted dictionary
sorted set in python

How is sorting for value types implemented in C#?

I cannot delete the (implicit) default constructor for structs to see that the compiler/runtime doesn't call it but I suspect it does a copy when sorting as even holding a temporary (value) to do a swap on implies a copy, though this could be achieved with pointers instead, but there is nothing I can see in the generics code to indicate it does anything special for value types vs reference types.

The IL

IL_0060: ldloc.0      // fooByValues
IL_0061: ldloc.1      // comparer
IL_0062: callvirt     instance void class [System.Collections]System.Collections.Generic.List`1<valuetype DevOpsCourse.Tests.Common.FunctionalComparerTest/FooByValue>::Sort(class [System.Runtime]System.Collections.Generic.IComparer`1<!0/*valuetype DevOpsCourse.Tests.Common.FunctionalComparerTest/FooByValue*/>)
IL_0067: nop          

Just refers to a virtual call I cannot look into so I have no idea how it is really implemented.

I couldn't find any documentation pertaining to this either.

To the question posed in the title, the answer is Yes.


You won't see anything special here. variables of value types hold the value within themselves. Any time you see any form of assignment to a variable of a value type, that's going to be a copy.

Variables of reference types hold references to the actual object that holds the data. When you perform an assignment to a variable of a reference type, you get a copy of the reference but the reference still refers to the same object.

That's why you won't see anything special here - it's all just assignments to variables that "do the right thing" for both value types and reference types.

(And reference types aren't passed by reference when used as parameters. Parameter passing is always pass by value by default, but what's being passed is a variable, not a value)


though this could be achieved with pointers instead

Bear in mind that most structs should be small anyway. Swapping pointers to them (even if such pointers existed) could well be more work than swapping the values because the pointers could well be larger than the struct.

E.g. an array of a value type is a chunk of memory containing the actual values - not a chunk of memory containing pointers to the values. The only way to swap the position of two such values is literally to overwrite them.

Array.Sort() sorts original array and not just copy, Contrast this with value types, which hold data within their own memory Create a new array that's the same length as the one "planets" points to What is the difference between a reference type and value type in c#?. The SORT control statement must be used when a sorting application is performed; this statement describes the control fields in the input records on which the program sorts. A SORT statement can also be used to specify a copy application. User labels will not be copied to the output data sets.

The sort algorithms in the BCL do create copies. They essentially do the same thing as in:

struct MyStruct { ... }

MyStruct a = ...;
MyStruct b = a; //copy

It's a simple assignment.

Struct constructors play no role here. .NET does not have the concept of a copy constructor. Also, the default constructor is not called here. Structs are always copied by simply copying all fields (essentially memcpy).

Even if assignments happen through pointers this still does the same thing. In fact an array access such as array[0] = array[1]; can done through an IL concept called a managed pointer. Using managed pointers you can obtain a pointer to a subject and directly read and write that subobject. C# now exposes this with their latest ref features. You can say:

MyStruct[] array = ...;
ref MyStruct item0 = ref array[0];
item0 = ...; //updates the array

This is safe, managed code.

Professional C# 2008, types, as in the following code segment, all values are copied, as you can see in where beatlesClone is created by calling the Clone() method from beatles. The Array class implements a quick-sort algorithm for sorting the elements in  Note: For best results, the range of cells that you sort should have column headings. Select any cell in the data range. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by box, select the first column that you want to sort.

The implementation of List<T>.Sort delegates to Array.Sort, which does create a temporary copy of the array member during swap operations. For value types, this would mean that values needing moved will be copied.

ECOOP '87. European Conference on Object-Oriented Programming: , If the behavior can be shared by several types, we suggest creating a separate type. the values of various fields, or whether the copy will have its own copies of Since sorting is a complex operation, and since it does not need to know very  When you see mixed word and number sorting that treats numbers correctly, it's because the sorting is more intelligent, and on top of that, still usually only works at the beginning or end of a string. improve this answer. answered Dec 30 '11 at 2:41. 90 silver badges. 143 bronze badges. That's the result when you sort strings of numbers

Professional C# 7 and .NET Core 2.0, the array are value types, as in the following code segment, all values are copied (see where beatlesClone is created by calling the Clone method from beatles. Sorting The Array class uses the Quicksort algorithm to sort the elements in  The SORT and MERGE statements change very little when you specify COPY. Just replace the information you usually put in parentheses with the word COPY: SORT FIELDS=COPY MERGE FIELDS=COPY. You can also specify COPY on the OPTION statement: OPTION COPY. All three of these statements have identical results.

How to create a shallow copy of SortedList Object in C# , The type of returned value will be Object. Note: A shallow copy of a collection copies only the elements of the collection, whether they are reference  As the preceding example shows, operations on a value-type variable affect only that instance of the value type, stored in the variable. If a value type contains a data member of a reference type, only the reference to the instance of the reference type is copied when a value-type instance is copied.

Sorting, Fields whose values do not have the proper form are sorted first. form is sorted in the proper numeric order whether or not its field type is numeric. the SORT RECORDS statement creates a sorted copy of the records to  Sorting algorithms are often referred to as a word followed by the word "sort," and grammatically are used in English as noun phrases, for example in the sentence, "it is inefficient to use insertion sort on large lists," the phrase insertion sort refers to the insertion sort sorting algorithm. 2 Classification. 3 Comparison of algorithms.

Comments
  • Structs are copied when passed as parameters, reference objects are passed by reference.
  • @Glubus I am aware of this
  • You could use a memory profiler and watch the number of objects being created.
  • What if you create your own struct and log something in their constructor?
  • @UweKeim This sounds very interesting, is there a known tool for this? If I cannot find documentation to confirm/deny my suspicion this would be the next best thing!
  • I always thought that an array of a value type is a chunk of memory containing pointers. Structs which are items of an array are stored in a heap, aren't they?
  • @YeldarKurmangaliyev - no, no pointers. Heap is usually irrelevant
  • Thanks for the clarification, this was the most informative (and the linked article is a gem).