Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using list arrays - Best practices

Tags:

c#

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);
like image 664
GuruMeditation Avatar asked Dec 02 '10 16:12

GuruMeditation


People also ask

Is it better to use arrays or lists?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.

When would you use a list over an array?

Data Types Storage: Array can store elements of only one data type but List can store the elements of different data types too. Hence, Array stores homogeneous data values, and the list can store heterogeneous data values.

Why are lists more efficient than arrays?

List occupies much more memory as every node defined the List has its own memory set whereas Arrays are memory-efficient data structure. A list is derived from Collection, which contains a more generic data type, whereas Array is fixed and store a more strong data type.

Is it better to use array or list C#?

In general, it's better to use lists in C# because lists are far more easily sorted, searched through, and manipulated in C# than arrays. That's because of all of the built-in list functionalities in the language.


2 Answers

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);
}
like image 130
dtb Avatar answered Oct 21 '22 17:10

dtb


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.

like image 23
Justin Niessner Avatar answered Oct 21 '22 18:10

Justin Niessner