Thursday, May 5, 2011

C#/.NET interview Question - Why is an array faster than an ArrayList?

Answer:

Let’s demonstrate an example to prove that how arrays are faster than arraylist for that go to visual studio and create a simple window application with a button and two labels like below diagram.




Below is the code snippet.
using System.Collections;// import this namespace to access arraylist.
using System.Diagnostics;// import this namespace to access Stopwatch.
namespace ArrayandArrayList
{
 public partial class Form1 : Form
 {
     int[] Array = new int[1000]; // here array is declared.
     ArrayList objArraylist = new ArrayList();// here array list is declared.
     public Form1()
     {
         InitializeComponent();
     }

     private void button1_Click(object sender, EventArgs e)
     {
         Stopwatch objWatch = new Stopwatch();
         Stopwatch objWatch1 = new Stopwatch();
         objWatch.Start();
         for(int i=0;i<1000;i++)
         {
             Array[i] = DateTime.Now.Second;
         }
         foreach (int i in Array)
         {

         }
         objWatch.Stop();
         label1.Text = objWatch.ElapsedTicks.ToString();
         objWatch1.Start();
         for (int i = 0; i < 1000; i++)
         {
             objArraylist.Add(DateTime.Now.Second.ToString());
         }
         foreach (object i in objArraylist)
         {
         }
         objWatch1.Stop();
         label2.Text = objWatch1.ElapsedTicks.ToString();
     }
 }
}

In the above code, I have used Stopwatch to record the time taken by the array and arraylist to performance actions.
The Output look like below diagram.



Conclusion: -As in ArrayList lots of Boxing and UnBoxing are done therefore its performance is slower than Array because in Array there is no type casting.

Please click here to see more c# and Dotnet interview questions

Regards,
Visit Authors blog for more Most asked c# interview questions

No comments: