I looked source code of the System.Linq namespace and I noticed that the ToArray method of the OrderedQueryable class created three arrays, but we could use one array for ordering. Why is this done??
-
2Seems like a question for Microsoft – Diado Jan 03 '20 at 08:50
1 Answers
This is because an allocation is not taking much time, it's a fixed-length operation in matter of time, independent from the size of the array.
Overall .NET Framework assumes we deal only with reasonable sizes, Arrays beyond 1 MB are rather seldom and the allocation of memory -for a short time - is a good compromise.
Additionally, there are very fast memory move operations built in in every CPU, the .NET Framework does not give direct access to those functions, but the internals do have access to it, they make use of pointers and direct transfer memory to memory, without managed code.
For a sorting operation, they choose the way via an index-map. An int is the most performant data-type of the cpu. (Although not smallest possible). This especially saves memory, if you have an array of structs. Imagine an array of 1000 Elements with a 300 byte long structure. Each swap of items would need to move 900 bytes !!! (300 to temporary, 300 from origin to destination, 300 from temporry to origin). With an index Map this is 12 bytes to move, and it's probably done in CPU registers. Probably 1000 times faster. So to have two arrays, plus an index, is the most optimal solution to minmize memory-move operations.
You are right, the implementation is not favouring the smallest memory use, but better performance.

- 2,446
- 1
- 14
- 13