code_junkie

Why is my IEnumerable<String> using yield return slower to iterate then List<String>

Nov 13th, 2011
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. public static IEnumerable<String> MyYieldCollection {
  2. get
  3. {
  4. wrapper.RunCommand("Fetch First From Water_Mains");
  5. for (int row = 0; row < tabinfo.GetNumberOfRows() ; row++) //GetNumberOfRows
  6. //will return 1000+ most of the time.
  7. {
  8. yield return wrapper.Evaluate("Water_Mains.col1");
  9. wrapper.RunCommand("Fetch Next From Water_Mains");
  10. }
  11. }
  12. }
  13.  
  14. public static List<String> MyListCollection
  15. {
  16. get
  17. {
  18. List<String> innerlist = new List<String>();
  19.  
  20. wrapper.RunCommand("Fetch First From Water_Mains");
  21. for (int row = 0; row < tabinfo.GetNumberOfRows(); row++)
  22. {
  23. innerlist.Add(wrapper.Evaluate("Water_Mains.col1"));
  24. wrapper.RunCommand("Fetch Next From Water_Mains");
  25. }
  26. return innerlist;
  27. }
  28. }
  29.  
  30. foreach (var item in MyYieldCollection) //Same thing for MyListCollection.
  31. {
  32. Console.WriteLine(item);
  33. }
  34.  
  35. Yield: 2000 (5000000)
  36. List: 2100 (5000000)
  37.  
  38. static void Main()
  39. {
  40. GC.Collect(GC.MaxGeneration,GCCollectionMode.Forced);
  41. int count1 = 0;
  42. var watch1 = Stopwatch.StartNew();
  43. for(int i = 0 ; i < 5000 ; i++) {
  44. foreach (var row in MyYieldCollection)
  45. {
  46. count1++;
  47. }
  48. }
  49. watch1.Stop();
  50.  
  51. GC.Collect(GC.MaxGeneration,GCCollectionMode.Forced);
  52. int count2 = 0;
  53. var watch2 = Stopwatch.StartNew();
  54. for (int i = 0; i < 5000; i++)
  55. {
  56. foreach (var row in MyListCollection)
  57. {
  58. count2++;
  59. }
  60. }
  61. watch1.Stop();
  62.  
  63. Console.WriteLine("Yield: {0} ({1})", watch1.ElapsedMilliseconds, count1);
  64. Console.WriteLine("List: {0} ({1})", watch2.ElapsedMilliseconds, count2);
  65. }
  66.  
  67. int rows = tabinfo.Rows.Count;
  68. for (int row = 0; row < rows; row++) {...}
  69.  
  70. public IEnumerable<int> YieldInts()
  71. {
  72. for (int i = 0; i < 1000; i++)
  73. {
  74. Thread.Sleep(1000) // or do some other work
  75. yield return i;
  76. }
  77. }
  78.  
  79. public void Main()
  80. {
  81. foreach(int i in YieldInts())
  82. {
  83. Console.WriteLine(i);
  84. if(i == 42)
  85. {
  86. break;
  87. }
  88. }
  89. }
Add Comment
Please, Sign In to add comment