开发者

Using list arrays - Best practices

I have a 开发者_高级运维c# newbie question. What is consider good practice out of the two below too? ...and is list slower or faster than the array?

        //Method 1
        int[] i_array = { 2, 0, 110, 53455, 2223 };

        if (someBolean)
        {
            Array.Resize(ref i_array, i_array.Length + 1);
            i_array[i_array.Length - 1] = someIntValue;
        }

        //Method 2
        var i_list = new List<int>();
        i_list.AddRange(new int[] { 2, 0, 110, 53455, 2223 });

        if (someBolean)
            i_list.Add(someIntValue);


Use lists when you need a collection that can grow or shrink.

Use arrays if you know the length and don't want to change it.


You can use collection initializers to initialize a list, so you get similar syntax to initializing an array:

var list = new List<int> { 2, 0, 110, 53455, 2223 };

if (someBoolean)
{
    list.Add(someIntValue);
}


The later is considered the best practice for variable size collections.

Depending on which type of collection you're using, the Framework class will do something internally similar to what you're doing in your first example (except instead of resizing by one element, it increments by a larger size so you have extra buffer space to keep adding elements).

In general, though, you don't want to re-invent the wheel. The framework provides a ton of collection classes that are variable size. Use them instead of writing your own.


A list uses an array internally so I'd expect the performance of these two to be the same.

It's a lot harder to make errors when programming with lists than raw arrays, so I'd prefer lists most of the time.


Both wind up as IEnumerables, so you can perform similar operations on both. The benefit of the List is as Justin Niessner said, variable size collections. Also, resizing an array would require the framework to reallocate memory, while the List behaves as a linked list, just adding or removing elements from collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜