Last active
August 29, 2015 13:59
-
-
Save wiennat/10731478 to your computer and use it in GitHub Desktop.
Comparison between foreach and while over IEnumerable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Diagnostics; | |
| namespace ForEachWhile | |
| { | |
| class Program | |
| { | |
| static IEnumerable<int> Foo(int n) | |
| { | |
| for (int i = 0; i < n; i++) | |
| { | |
| yield return i; | |
| } | |
| } | |
| static void Main(string[] args) | |
| { | |
| IEnumerable<int> testForEach = Foo(10000000); | |
| IEnumerable<int> testWhile = Foo(10000000); | |
| IEnumerator<int> iterator = testWhile.GetEnumerator(); | |
| Stopwatch sw = new Stopwatch(); | |
| sw.Start(); | |
| foreach (var item in testForEach) | |
| { | |
| } | |
| sw.Stop(); | |
| Console.WriteLine("foreach " + sw.ElapsedTicks); | |
| sw.Restart(); | |
| while (iterator.MoveNext()) | |
| { | |
| int item = iterator.Current; | |
| } | |
| sw.Stop(); | |
| Console.WriteLine("while " + sw.ElapsedTicks); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| foreach while | |
| 297842 277067 | |
| 297586 278804 | |
| 299227 278911 | |
| 298107 276781 | |
| 298082 278367 | |
| 297696 277470 | |
| 297788 277902 | |
| 299118 278959 | |
| 295432 276546 | |
| 297956 278808 | |
| avg ticks | |
| foreach: 297883 | |
| while: 277962 | |
| median | |
| foreach: 297899 | |
| while: 278136 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment