using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace ElementAtOrIndex { class Program { // Declare/initialize static variables. static Stopwatch timer = new Stopwatch(); static List ElementAtTimes = new List(); static List IndexTimes = new List(); static void Main(string[] args) { // Declare/initialize variables. int[] array; int count = 1000000; int iterations = 100; // Just initializes a list with elements from 0 to count. // Slower than for loops, but pithy for an example on SO. List list = Enumerable.Range(0, count).ToList(); // Assert that both methods are equal. for (int i = 0; i < list.Count; i++) { if (list.ElementAt(i) != list[i]) { Console.WriteLine("Both methods are not equal!"); Environment.Exit(1); } } Console.WriteLine("Both methods are equal!"); // Time ElementAt access *iterations* times by copying into an array. for (int i = 0; i < iterations; i++) { // [Re]initialize the array. array = new int[count]; // Start the timer. timer.Start(); for (int j = 0; j < list.Count; j++) array[j] = list.ElementAt(j); // Explicitly stop the timer. timer.Stop(); // Note the time. ElementAtTimes.Add(timer.ElapsedMilliseconds); timer.Reset(); } timer.Reset(); // Time Index access *iterations* times by copying into an array. for (int i = 0; i < iterations; i++) { // [Re]initialize the array. array = new int[count]; // Start the timer. timer.Start(); for (int j = 0; j < list.Count; j++) array[j] = list[j]; // Explicitly stop the timer. timer.Stop(); // Note the time. IndexTimes.Add(timer.ElapsedMilliseconds); timer.Reset(); } // Output times. Console.WriteLine("Average time for ElementAt access iteration: {0} ms", ElementAtTimes.Average()); Console.WriteLine("Average time for Index access iteration: {0} ms", IndexTimes.Average()); Console.ReadLine(); } } }