vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Thursday, October 25, 2012

Difference and performance between Array and ArrayList in C#



Arrays:
  • Arrays are fixed size .
  • It’s used the namespace as System.
  • Array cannot resize automatically.
  • But in Vb.net array can resize themself by using ReDim Statement.When using ReDime array can losses the data and its modify the array structure as mention in the ReDim statement.
  • But this ReDim statement is not available in C#.
  • Array has contains one data type i.e. Homogenous data type.
  • Arrays are multidimensional.
  • The data in an array is accessed by indexes.
  • For performance always recommended using arrays.
  • If you delete an item in an array, it keeps that position empty, its wait for anther data to fill the positions.

Syntax:
string[] str = new string[5];
            str[0] = "DotNet";
            str[1] = "DotnetCode";           

ArrayList:
  • ArrayList are variable in size.
  • It’s used the namespace as System .Collections
  • ArrayList grows automatically i.e. the numbers of items are added to the arrayList.
  • ArrayList contain many data types i.e. heterogenous data type. In a single Arraylist we can store any data type - integer, string and any type of object inherited from System.Object. 
  • ArrayList is always single-dimensional.
  • If you delete an item in an arraylist, that position is occupied by the next element. 
  • We can add, insert and delete items into an ArrayList.

Syntax:

ArrayList astr = new ArrayList();
            astr.Add("str");
            astr.Remove("str");
            astr.RemoveAt(0);


Check the performance between Array and ArrayList in C#

        int[] rate = new int[501];
        ArrayList str1 = new ArrayList();

        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i <= 500; i++)
        {
            rate[i] = i;
        }
        watch.Stop();
        Response.Write("ARRAY SECONDS :" + watch.Elapsed.TotalMilliseconds);

watch.Reset();
        watch.Start();
        for (int i = 0; i <= 500; i++)
        {
            str1.Add(i);
        }
        watch.Stop();
        Response.Write("ARRAYLIST SECONDS :" + watch.Elapsed.TotalMilliseconds);

Result :

When compare Performance array is better than ArrayList

ARRAY SECONDS :0.0035ARRAYLIST SECONDS :0.0194
Post your comments here….

0 comments:

Post a Comment