Performance comparison between LinkedList and ToArray
Some weeks ago I created an article comparing the performance of ToList versus ToArray when creating short lived collections that won’t be mutated, usually used to prevent multiple enumerations when iterating over a temporary LINQ transformation or to ensure mapping exceptions will be thrown inside the corresponding application layer.
In that article I concluded ToArray is faster and more memory efficient than ToList for almost any collection sizes and in any .NET version — tests were conducted on .NET Framework 4.8, .NET 7 and .NET 8.
But then I began to wonder:If I’m creating a temporary collection of unknown size just to force enumeration, wouldn’t LinkedList be a more efficient collection since I’m only appending items to the end, which is O(1), instead of constantly allocating new arrays like ToArray does?
I believe that’s a valid point so I decided to do a performance comparison between the two, assuming ToArray as the baseline and try to give a detailed explanation for the observed results.
Performance test
The test consists in the creation of a collection that holds random integers, being the size defined by a parameter. To ensure the randomness does not affect the results, the values are cached into an array and, before invoking either ToArray or creating the LinkedList, they are converted into a new IEnumerable, not just a cast that could lead to internal optimizations.
This time I decided to do the performance comparison only on .NET Framework 4.8 and .NET 8.
Because we want to decide, for a given application, between ToArray or LinkedList based on performance, let’s analyze the results for each framework version.
The ToArray method is significantly faster and more memory efficient than creating a new LinkedList. Still, it does allocate more Gen2 memory for larger collections which may be something to consider.
Same behavior as .NET Framework 4.8, being the ToArray method much faster and memory efficient while still allocating more Gen2 memory on larger collections.
.NET performance evolution
Since in my previous article I already covered the performance evolution of ToArray over the years, let’s just compare how initializing a LinkedList from an IEnumerable have changed for different frameworks.
On average, .NET 8 is 51% faster than .NET Framework 4.8, a clear demonstration how performance has improved over the years.
Analyzing the results
Now that we have the results you are probably questioning why does a LinkedList use more memory and is slower than ToArray? Since we don’t know the collection size, shouldn’t the constant allocation of new arrays and then a final copy to a trimmed one be slower and take more memory?
Using more memory could actually be expectable since a LinkedList, for each item, creates a class that holds a reference for the previous and next node, but why is it slower since adding an item is always a O(1) operation?
var current = new T[sizeIncrease]; var count = 0; foreach (var item in items) { if (count == current.Length) { var previous = current; current = new T[previous.Length + sizeIncrease]; previous.CopyTo(current, 0); }
It assumes the ToArray method behaves similar to a List, creating a bigger one every time the current is full and doing a copy, and in the end it trims the excess.
In reality, the implementation is more similar to this:
var current = new T[sizeIncrease]; var count = 0; var idx = 0;
foreach (var item in items) { if (idx == sizeIncrease) { arrayBuffer.Enqueue(current); current = new T[sizeIncrease]; idx = 0; }
current[idx++] = item; ++count; }
if (count is0) return Array.Empty<T>();
var currentIdx = idx;
idx = 0; var final = new T[count]; while (arrayBuffer.Count > 0) { var previous = arrayBuffer.Dequeue(); previous.CopyTo(final, idx); idx += previous.Length; }
Array.Copy(current, 0, final, idx, currentIdx);
return final; }
Instead of creating a bigger array every time it’s full and copying all items, it actually creates a buffer that stores the previously allocated arrays and when the iteration finishes it copies everything in sequence to the final array that has the expected size.
The actual ToArray method implementation as a lot of optimizations, for example, when an ICollection is received they can initialize a new array with the collection size and just call CopyTo. It also doesn’t use a Queue to keep track of previous initialized arrays but instead a simple version of a LinkedList concept.
In this article we compared the performance of initializing a LinkedList versus using ToArray and concluded that, on theory, LinkedList looked like a good fit when creating short lived collections were enumeration must be forced because of its O(1) nature when appending values, but due to internal optimizations of ToArray and since indexing is just faster while using less memory it significantly compensates having to allocate multiple arrays and copying their content.
Keep in mind that LinkedList still has its place, specially when storing collections too big to be stored into a single memory section and it’s nice to see that .NET keeps improving its performance.