Advertisement
Guest User

Untitled

a guest
Sep 13th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. foreach (var item in items) {}
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7.  
  8. namespace ArrayTest
  9. {
  10. public class Foo
  11. {
  12. public string Bar1 { get; set; }
  13. public string Bar2 { get; set; }
  14. public string Bar3 { get; set; }
  15. public string Bar4 { get; set; }
  16. public string Bar5 { get; set; }
  17. }
  18.  
  19. class Program
  20. {
  21. const int Size = 10000000;
  22. static readonly List<string> Output = new List<string>();
  23. static readonly List<string> Print = new List<string>();
  24.  
  25. static void Main()
  26. {
  27. var foo1 = GetFoo1();
  28. var foo2 = GetFoo2();
  29.  
  30. UseArray(foo1);
  31. UseIEnumerable(foo2);
  32.  
  33. // Get random element from the list. Just for avoiding compiler optimization.
  34. int i = new Random().Next(Output.Count);
  35. Console.WriteLine(Output[i]);
  36.  
  37. foreach (string o in Print)
  38. {
  39. Console.WriteLine(o);
  40. }
  41. }
  42.  
  43. private static void WriteLine(string x)
  44. {
  45. Output.Add(x);
  46. }
  47.  
  48. private static Foo[] GetFoo1()
  49. {
  50. Stopwatch sw = Stopwatch.StartNew();
  51. var foo1 = new Foo[Size];
  52. for (int i = 0; i < Size; i += 1)
  53. {
  54. var foo = new Foo { Bar1 = "Bar1", Bar2 = "Bar2", Bar3 = "Bar3", Bar4 = "Bar4", Bar5 = "Bar5" };
  55. foo1[i] = foo;
  56. }
  57. sw.Stop();
  58. Print.Add(string.Format("CreateArray: {0}", sw.ElapsedMilliseconds));
  59. return foo1;
  60. }
  61.  
  62. private static IEnumerable<Foo> GetFoo2()
  63. {
  64. Stopwatch sw = Stopwatch.StartNew();
  65. for (int i = 0; i < Size; i += 1)
  66. {
  67. var foo = new Foo {Bar1 = "Bar1", Bar2 = "Bar2", Bar3 = "Bar3", Bar4 = "Bar4", Bar5 = "Bar5"};
  68. yield return foo;
  69. }
  70. sw.Stop();
  71. Print.Add(string.Format("CreateIEnumerable: {0}", sw.ElapsedMilliseconds));
  72. }
  73.  
  74. static void UseArray<T>(T[] values)
  75. {
  76. Stopwatch sw = Stopwatch.StartNew();
  77. var count = values.Length;
  78. foreach (object o in values)
  79. {
  80. var x = (Foo)o;
  81. WriteLine(x.Bar1);
  82. }
  83. sw.Stop();
  84. Print.Add(string.Format("UseArray: {0}, count: {1}", sw.ElapsedMilliseconds, count));
  85. }
  86.  
  87. static void UseIEnumerable<T>(IEnumerable<T> values)
  88. {
  89. Stopwatch sw = Stopwatch.StartNew();
  90. var count = values.Count();
  91. foreach (object o in values)
  92. {
  93. var x = (Foo)o;
  94. WriteLine(x.Bar1);
  95. }
  96. sw.Stop();
  97. Print.Add(string.Format("UseIEnumerable: {0}, count: {1}", sw.ElapsedMilliseconds, count));
  98. }
  99. }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement