8

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);
Singleton
  • 3,701
  • 3
  • 24
  • 37
GuruMeditation
  • 1,852
  • 4
  • 16
  • 14
  • 1
    if you constantly resizing the array, might as well use list in method 2. – Eric K Yung Dec 02 '10 at 16:40
  • I know it's difficult to do but that this stage on the learning curve, don't worry about performance *until performance is an issue*. See this question for http://stackoverflow.com/questions/211414/is-premature-optimization-really-the-root-of-all-evil – Binary Worrier Dec 02 '10 at 16:58

4 Answers4

11

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);
}
dtb
  • 213,145
  • 36
  • 401
  • 431
5

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3

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.

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
0

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.

CodeMonkey1313
  • 15,717
  • 17
  • 76
  • 109