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. timer.Reset();
  55. }
  56.  
  57. timer.Reset();
  58.  
  59. // Time Index access *iterations* times by copying into an array.
  60. for (int i = 0; i < iterations; i++)
  61. {
  62. // [Re]initialize the array.
  63. array = new int[count];
  64.  
  65. // Start the timer.
  66. timer.Start();
  67.  
  68. for (int j = 0; j < list.Count; j++)
  69. array[j] = list[j];
  70.  
  71. // Explicitly stop the timer.
  72. timer.Stop();
  73.  
  74. // Note the time.
  75. IndexTimes.Add(timer.ElapsedMilliseconds);
  76. timer.Reset();
  77. }
  78.  
  79. // Output times.
  80. Console.WriteLine("Average time for ElementAt access iteration: {0} ms", ElementAtTimes.Average());
  81. Console.WriteLine("Average time for Index access iteration: {0} ms", IndexTimes.Average());
  82.  
  83. Console.ReadLine();
  84. }
  85. }
  86. }
Success #stdin #stdout 4.19s 67968KB
stdin
Standard input is empty
stdout
Both methods are equal!
Average time for ElementAt access iteration: 26.35 ms
Average time for Index access iteration: 11.05 ms