fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5.  
  6. namespace BenchLinqLoops
  7. {
  8. class MainClass
  9. {
  10. const int COUNT = 1000;
  11. const int REPEAT = 10000;
  12.  
  13. public static void Main (string[] args)
  14. {
  15. Console.WriteLine ("Benchmarking Linq Loops");
  16.  
  17. var buffer = new List<int> (COUNT);
  18. for (int i = 0; i < COUNT; i++) {
  19. buffer.Add (i);
  20. }
  21. IEnumerable<string> result;
  22. var sw = new Stopwatch ();
  23.  
  24. Console.Write ("LinqAddXToEven3Loops on {0} with {1} repeats ... ", COUNT, REPEAT);
  25. sw.Restart ();
  26. for (int i = 0; i < REPEAT; i++) {
  27. result = LinqAddXToEven3Loops (buffer, i);
  28. }
  29. sw.Stop ();
  30. Console.WriteLine ("{0}", sw.Elapsed);
  31.  
  32. Console.Write ("LinqAddXToEven2Loops on {0} with {1} repeats ... ", COUNT, REPEAT);
  33. sw.Restart ();
  34. for (int i = 0; i < REPEAT; i++) {
  35. result = LinqAddXToEven2Loops (buffer, i);
  36. }
  37. sw.Stop ();
  38. Console.WriteLine ("{0}", sw.Elapsed);
  39.  
  40. Console.Write ("SQLAddXToEven on {0} with {1} repeats ... ", COUNT, REPEAT);
  41. sw.Restart ();
  42. for (int i = 0; i < REPEAT; i++) {
  43. result = SQLAddXToEven (buffer, i);
  44. }
  45. sw.Stop ();
  46. Console.WriteLine ("{0}", sw.Elapsed);
  47.  
  48. Console.Write ("YieldAddXToEven on {0} with {1} repeats ... ", COUNT, REPEAT);
  49. sw.Restart ();
  50. for (int i = 0; i < REPEAT; i++) {
  51. result = YieldAddXToEven (buffer, i);
  52. }
  53. sw.Stop ();
  54. Console.WriteLine ("{0}", sw.Elapsed);
  55. }
  56.  
  57. static IEnumerable<string> LinqAddXToEven3Loops (IEnumerable<int> buffer, int x)
  58. {
  59. return buffer.Where (n => (n % 2) == 0).Select (n => n + x).Select (n => string.Format("Hello {0}", n));
  60. }
  61.  
  62. static IEnumerable<string> LinqAddXToEven2Loops (IEnumerable<int> buffer, int x)
  63. {
  64. return buffer.Where (n => (n % 2) == 0).Select (n => string.Format("Hello {0}", n + x));
  65. }
  66.  
  67. static IEnumerable<string> SQLAddXToEven (IEnumerable<int> buffer, int x)
  68. {
  69. return from n in buffer
  70. where (n % 2) == 0
  71. select string.Format ("Hello {0}", n + x);
  72. }
  73.  
  74. static IEnumerable<string> YieldAddXToEven (IEnumerable<int> buffer, int x)
  75. {
  76. foreach (var n in buffer) {
  77. if ((n % 2) == 0) {
  78. yield return string.Format ("Hello {0}", n + x);
  79. }
  80. }
  81. }
  82. }
  83. }
  84.  
Success #stdin #stdout 0.06s 24072KB
stdin
Standard input is empty
stdout
Benchmarking Linq Loops
LinqAddXToEven3Loops on 1000 with 10000 repeats ... 00:00:00.0184278
LinqAddXToEven2Loops on 1000 with 10000 repeats ... 00:00:00.0023821
SQLAddXToEven on 1000 with 10000 repeats ... 00:00:00.0026071
YieldAddXToEven on 1000 with 10000 repeats ... 00:00:00.0006225