fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5.  
  6. namespace ElementAtOrIndex
  7. {
  8. class Program
  9. {
  10. // Declare/initialize static variables.
  11. static Stopwatch timer = new Stopwatch();
  12. static List<long> ElementAtTimes = new List<long>();
  13. static List<long> IndexTimes = new List<long>();
  14.  
  15. static void Main(string[] args)
  16. {
  17. // Declare/initialize variables.
  18. int[] array;
  19. int count = 1000000;
  20. int iterations = 100;
  21.  
  22. // Just initializes a list with elements from 0 to count.
  23. // Slower than for loops, but pithy for an example on SO.
  24. List<int> list = Enumerable.Range(0, count).ToList<int>();
  25.  
  26. // Assert that both methods are equal.
  27. for (int i = 0; i < list.Count; i++)
  28. {
  29. if (list.ElementAt(i) != list[i])
  30. {
  31. Console.WriteLine("Both methods are not equal!");
  32. Environment.Exit(1);
  33. }
  34. }
  35. Console.WriteLine("Both methods are equal!");
  36.  
  37. // Time ElementAt access *iterations* times by copying into an array.
  38. for (int i = 0; i < iterations; i++)
  39. {
  40. // [Re]initialize the array.
  41. array = new int[count];
  42.  
  43. // Start the timer.
  44. timer.Start();
  45.  
  46. for (int j = 0; j < list.Count; j++)
  47. array[j] = list.ElementAt(j);
  48.  
  49. // Explicitly stop the timer.
  50. timer.Stop();
  51.  
  52. // Note the time.
  53. ElementAtTimes.Add(timer.ElapsedMilliseconds);
  54. }
  55.  
  56. // Time Index access *iterations* times by copying into an array.
  57. for (int i = 0; i < iterations; i++)
  58. {
  59. // [Re]initialize the array.
  60. array = new int[count];
  61.  
  62. // Start the timer.
  63. timer.Start();
  64.  
  65. for (int j = 0; j < list.Count; j++)
  66. array[j] = list[j];
  67.  
  68. // Explicitly stop the timer.
  69. timer.Stop();
  70.  
  71. // Note the time.
  72. IndexTimes.Add(timer.ElapsedMilliseconds);
  73. }
  74.  
  75. // Output times.
  76. Console.WriteLine("Average time for ElementAt access iteration: {0} ms", ElementAtTimes.Average());
  77. Console.WriteLine("Average time for Index access iteration: {0} ms", IndexTimes.Average());
  78.  
  79. Console.ReadLine();
  80. }
  81. }
  82. }
  83.  
Success #stdin #stdout 4.17s 66944KB
stdin
Standard input is empty
stdout
Both methods are equal!
Average time for ElementAt access iteration: 1334.65 ms
Average time for Index access iteration: 3254.34 ms