.NET — ToList vs ToArray
Performance comparison between ToList and ToArray
--
Ever since Microsoft introduced Language Integrated Query to the .NET framework (also known as LINQ) developers have been using it extensively to work with collections.
From a simple filter, to an aggregation, to a transformation, LINQ is the technology of choice to keep code clean and readable. We even have providers that convert LINQ instructions into SQL commands that will be run in some database.
One of the coding guidelines for the applications I manage dictates the following:
Always use
IReadOnlyCollection
instead ofIEnumerable
when passing collections between application layers andToArray
should be used to force the enumeration.
Because we developers are curious by default and need to understand why things are implemented in a given way, every time we have a new team member, that coding guideline usually leads to the following conversation:
Q: Why do we use
IReadOnlyCollection
in POCOs instead ofIEnumerable
?A: Well, because we want the contracts to clearly state the collection is in memory, hence no multiple enumerations will occur, and any mapping problems will happen in the corresponding layer.
Q: Fair enough, but why
ToArray
? That interface is implemented by arrays and lists, I could be usingToList
and have the same result.A: The result is the same, that’s a fact, but
ToArray
is usually faster and more memory efficient thanToList
, and since it’s a short lived collection that won’t be mutated, the former is preferred.
In this article I’m going to compare the performance of ToList
versus ToArray
when creating short lived collections. I’m also going to execute the test in different versions of the framework (.NET Framework 4.8, .NET 7 and .NET 8) so we can also see how much the performance have improved over the years.
I’m going to use the well known C# library BenchmarkDotNet
to run the tests and the environment will be the following:
BenchmarkDotNet v0.13.10, Windows 11 (10.0.22621.2428/22H2/2022Update/SunValley2)
AMD Ryzen 7 3700X, 1 CPU, 16 logical and 8 physical cores
.NET SDK 8.0.100-rc.2.23502.2…