What’s the best way to build an array?
I’m writing a method that adds a bunch of stuff to an array (of strings) and then returns it. Right now, I’ve just used a List<string> and then .Add stuff to it, and then return list.ToArray(). I don’t know the length of the array beforehand (unless of course I use a 2-pass algorithm, once just to compute the size). Is that a good way to do it, or is there a more efficient way?
PS: I don’t want to yield an enumerable.
If you want to build an array of unknown size, your current approach is perfect. Just add elements to a
List<T>and callToArray()at the end.The one thing you could, potentially do, however, is “guess” at the final size. If you know you’ll be adding a certain range of elements, constructing the list to that appropriate capacity (or slightly larger) may prevent or reduce reallocations during the construction process.
For example, if you suspect that you’ll have about 100 elements, you would be better off doing:
Otherwise, the list will need to resize itself as items are added.