Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5.  
  6. namespace SkipWhilePerf
  7. {
  8. public static class Program
  9. {
  10. private static readonly Stopwatch s_watch = new Stopwatch();
  11.  
  12. static void Start() { s_watch.Restart(); }
  13. static void Stop() { s_watch.Stop(); Console.WriteLine(s_watch.Elapsed); }
  14. static void Restart() { Stop(); Start(); }
  15.  
  16. public static void Main()
  17. {
  18. int[] array = Enumerable.Range(1, 1000000).ToArray();
  19.  
  20. // old
  21. Start();
  22.  
  23. foreach (var foo in array.OldSkipWhile(i => i < 500000));
  24.  
  25. Restart();
  26.  
  27. foreach (var foo in array.OldSkipWhile((i, index) => i < 500000 && index < 500000));
  28.  
  29. // new
  30. Restart();
  31.  
  32. foreach (var bar in array.NewSkipWhile(i => i < 500000));
  33.  
  34. Restart();
  35.  
  36. foreach (var bar in array.NewSkipWhile((i, index) => i < 500000 && index < 500000));
  37.  
  38. Stop();
  39. }
  40.  
  41. public static IEnumerable<T> OldSkipWhile<T>(this IEnumerable<T> src, Func<T, bool> func)
  42. {
  43. bool yielding = false;
  44. foreach (T element in src)
  45. {
  46. if (!yielding && !func(element)) yielding = true;
  47. if (yielding) yield return element;
  48. }
  49. }
  50.  
  51. public static IEnumerable<T> OldSkipWhile<T>(this IEnumerable<T> src, Func<T, int, bool> func)
  52. {
  53. int index = -1;
  54. bool yielding = false;
  55. foreach (T element in src)
  56. {
  57. checked { index++; }
  58. if (!yielding && !func(element, index)) yielding = true;
  59. if (yielding) yield return element;
  60. }
  61. }
  62.  
  63. public static IEnumerable<T> NewSkipWhile<T>(this IEnumerable<T> src, Func<T, bool> func)
  64. {
  65. using (IEnumerator<T> e = src.GetEnumerator())
  66. {
  67. do
  68. if (!e.MoveNext()) yield break;
  69. while (func(e.Current));
  70. do
  71. yield return e.Current;
  72. while (e.MoveNext());
  73. }
  74. }
  75.  
  76. public static IEnumerable<T> NewSkipWhile<T>(this IEnumerable<T> src, Func<T, int, bool> func)
  77. {
  78. int index = -1;
  79. using (IEnumerator<T> e = src.GetEnumerator())
  80. {
  81. do
  82. {
  83. if (!e.MoveNext()) yield break;
  84. checked { index++; }
  85. } while (func(e.Current, index));
  86. do
  87. yield return e.Current;
  88. while (e.MoveNext());
  89. }
  90. }
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement