Detailed comparison of arrays Array ArrayList and generic List in C

  • 2021-10-15 11:19:53
  • OfStack

In C #, arrays Array, ArrayList and generic List can all store a group of objects, but we don't know which one has the highest performance in development. Let's analyze it slowly.

1. Array Array

An array is a fixed-size sequential collection of elements of the same type. An array is a collection used to store data. It is generally considered as a collection of variables of the same type.

The Array class is the base class for all arrays in C # and is defined in the System namespace.

Arrays are stored contiguously in memory, so their indexing speed is very fast, and it is very simple to assign values and modify elements.

Specific usage of Array array:


using System;

namespace WebApp
{
  class Program
  {
    static void Main(string[] args)
    {
      //System.Array
      //1 Array []  Specific type, fixed length 
      string[] str1 = new string[3];
      str1[0] = "a";
      str1[1] = "b";
      str1[2] = "c";
      Console.WriteLine(str1[2]);

      string[] str2 = new string[] { "a", "b", "c" };
      Console.WriteLine(str2[0]);

      string[] str3 = { "a", "b", "c" };
      Console.WriteLine(str3[0]);
      //2 , 2 Dimensional array 
      //int[,] intArray=new int[2,3]{{1,11,111},{2,22,222}};
      int[,] intArray = new int[2, 3];
      intArray[0, 0] = 1;
      intArray[0, 1] = 11;
      intArray[0, 2] = 111;

      intArray[1, 0] = 2;
      intArray[1, 1] = 22;
      intArray[1, 2] = 222;
      Console.WriteLine("{0},{1},{2}", intArray[0, 0], intArray[0, 1], intArray[0, 2]);
      Console.WriteLine("{0},{1},{2}", intArray[1, 0], intArray[1, 1], intArray[1, 2]);

      //3 Multidimensional array 
      int[, ,] intArray1 = new int[,,]
      {
        {{1, 1}, {11, 11}, {111, 111}},
        {{2, 2}, {22, 22}, {222, 222}},
        {{3, 3}, {33, 33}, {333, 333}}
      };
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[0, 0, 0], intArray1[0, 0, 1], intArray1[0, 1, 0], intArray1[0, 1, 1],
        intArray1[0, 2, 0], intArray1[0, 2, 1]);
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[1, 0, 0], intArray1[1, 0, 1], intArray1[1, 1, 0], intArray1[1, 1, 1],
        intArray1[1, 2, 0], intArray1[1, 2, 1]);
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[2, 0, 0], intArray1[2, 0, 1], intArray1[2, 1, 0], intArray1[2, 1, 1],
        intArray1[2, 2, 0], intArray1[2, 2, 1]);

      //4 Interleaved arrays are arrays of arrays 
      int[][] intArray2 = new int[4][];
      intArray2[0] = new int[] { 1 };
      intArray2[1] = new int[] { 2, 22 };
      intArray2[2] = new int[] { 3, 33, 333 };
      intArray2[3] = new int[] { 4, 44, 444,4444 };
      for (int i = 0; i < intArray2.Length; i++)
      {
        for (int j = 0; j < intArray2[i].Length; j++)
        {
          Console.WriteLine("{0}", intArray2[i][j]);
        }
      }


      Console.ReadKey();
    }
  }
}

Although arrays store retrieved data quickly, they also have one disadvantage:

1. When declaring an array, you must specify the length of the array. If you don't know the length of the array, it will become very troublesome.

2. The length of the array is too long, which will cause memory waste; Too short will cause data overflow error.

3. It is troublesome to insert data between two data in an array

Refer to Microsoft Official Documentation: Array Class (System)

2. ArrayList

Since arrays have many disadvantages, C # provides ArrayList objects to overcome them.

ArrayList is under the namespace System. Collections, which must be referenced when using this class. At the same time, it inherits the IList interface and provides data storage and retrieval.

The size of an ArrayList object is dynamically expanded and contracted according to the data stored in it. Therefore, when declaring an ArrayList object, you do not need to specify its length.

The default initial capacity of ArrayList is 0. As elements are added to the ArrayList, capacity is automatically increased by reallocation as needed. You can reduce capacity by calling TrimToSize or by explicitly setting the Capacity property.


using System;
using System.Collections;
public class SamplesArrayList {

  public static void Main() {

   ArrayList myAL = new ArrayList();
   myAL.Add("Hello");
   myAL.Add("World");
   myAL.Add("!");

   Console.WriteLine( "myAL" );
   Console.WriteLine( "  Count:  {0}", myAL.Count );
   Console.WriteLine( "  Capacity: {0}", myAL.Capacity );
   Console.Write( "  Values:" );
   PrintValues( myAL );
  }

  public static void PrintValues( IEnumerable myList ) {
   foreach ( Object obj in myList )
     Console.Write( "  {0}", obj );
   Console.WriteLine();
   Console.ReadKey();
  }

}

Run results:

ArrayList addresses all of the drawbacks in arrays, but boxing and unboxing often occur when storing or retrieving value types, resulting in significant performance drawbacks. Especially boxing operations, such as:


      ArrayList list = new ArrayList();

      //add 
      list.Add("joye.net");
      list.Add(27);

      //update 
      list[2] = 28;

      //delete 
      list.RemoveAt(0);

      //Insert 
      list.Insert(0, "joye.net1"); 

In List, the string joye. net is inserted first, and int type 27 is inserted. In this way, it is allowed to insert different types of data in ArrayList. Because ArrayList treats all data inserted into it as object type, when using ArrayList to process data, it is likely to report a type mismatch error, that is, ArrayList is not type safe.

Refer to Microsoft's official ArrayList documentation: ArrayList class (System. Collections)

3. Generic List < T >

Because ArrayList has the disadvantages of insecure types and boxed and unpacked, the concept of generics appears.

The List class is a generic equivalent of the ArrayList class. This class implements the IList generic interface using arrays whose size can be dynamically increased on demand, and most of its usage is similar to ArrayList.

List < T > Is type-safe, and when you declare an List collection, you must declare for it the object type of the data within the List collection.


using System;
using System.Collections.Generic;

public class Example
{
  public static void Main()
  {
    List<string> dinosaurs = new List<string>();

    Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

    dinosaurs.Add("Tyrannosaurus");
    dinosaurs.Add("Amargasaurus");
    dinosaurs.Add("Mamenchisaurus");
    dinosaurs.Add("Deinonychus");
    dinosaurs.Add("Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);

    Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
      dinosaurs.Contains("Deinonychus"));

    Console.WriteLine("\nInsert(2, \"Compsognathus\")");
    dinosaurs.Insert(2, "Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

    Console.WriteLine("\nRemove(\"Compsognathus\")");
    dinosaurs.Remove("Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    dinosaurs.TrimExcess();
    Console.WriteLine("\nTrimExcess()");
    Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);

    dinosaurs.Clear();
    Console.WriteLine("\nClear()");
    Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);
  }
}

If the object type of the data in the List collection is declared to be string, and then 111 of int type is inserted into the List collection, IDE will report an error and fail to compile. Obviously, List < T > Is type safe.

To re-encapsulate the returned result set:


  public class ResultDTO<T>
  {
    public T Data { get; set; }
    public string Code { get; set; }
    public string Message { get; set; }
  }

      var data = new CityEntity();
      return new ResultDTO<CityEntity> { Data = data, Code = "1", Message = "sucess"};

      var data2 = new List<CityEntity>();
      return new ResultDTO<List<CityEntity>> { Data = data2, Code = "1", Message = "sucess" };

      var data1 = 1;
      return new ResultDTO<int> { Data = data1, Code = "1", Message = "sucess" };

Refer to Microsoft official document: List generic class for more

4. Summary

1. The size of the array is fixed, while ArrayList or List < T > The capacity of can be automatically expanded as needed.

2. Arrays can have multiple dimensions, and ArrayList or List < T > There is always only one dimension. (You can create an array list or a list of lists)

3. The performance of certain types of arrays is better than that of ArrayList (excluding Object, because the elements of ArrayList are Object, and boxing and unboxing operations usually occur when storing or retrieving value types).

4. ArrayList and List < T > Basically equivalent if List < T > If the type T of the class is a reference type, the behavior of the two classes is exactly the same. If T is a value type, you need to consider the performance loss caused by packing and unpacking. List < T > Is type safe.


Related articles: