C# Array Builder?
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. Rig开发者_开发知识库ht 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 call ToArray()
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:
var temporaryList = new List<string>(120);
Otherwise, the list will need to resize itself as items are added.
I'd suggest this is an interface problem. Instead of returning an array, return either an IEnumberable<string>
or IList<string>
(arrays implement IList<T>
, so from an implementation detail, an array and List<T>
would be indistinguishable).
If you're stuck with an array in the interface and don't know the size ahead of time, your existing solution is the best solution of which I'm aware.
精彩评论