I want to convert
var aList = new List<string>(new string[] { "elem1", "elem2", "elem3" });
initializations into
var aList = new List<string>() { "elem1", "elem2", "elem3" };
in our source code. I believe that the latter doesn't have unnecessary array creation and array -> List conversion. Or the former has too? Or the compiler optimize it out anyway? Can I face any undesirable side effects (or lack of side effects) later?
The project uses .NET 4.
They are not entirely equivalent.
In the first case you're creating a new array, then passing that to the List<T>
constructor, which will create it's own internal array of the same size and invoke the source array's CopyTo
method to copy items out of the source array and into it's internal array.
In the second case you construct a new List<T>
with an initially empty array (of size _defaultCapacity = 4
), and then invoking the List's Add
method, which can cause the internal array to be resized several times as it's adding elements.
So in the first case, you benefit from not having to resize the List's internal array, as well as calling the potentially more efficient CopyTo
method, rather than an iterative Add
, at the cost of having to create two arrays in memory at once.
Here's one thing you could do to avoid creating two arrays and ensure you don't have resize the list's internal array:
var aList = new List<string>(3) { "elem1", "elem2", "elem3" };
I wouldn't necessarily recommend this for production code, due to the magic constant 3
, but then again, you've already got three other magic constants there anyway.