Created
March 23, 2013 16:29
-
-
Save david-mclean/5228317 to your computer and use it in GitHub Desktop.
An example of using yield.
This file contains 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; | |
using System.Threading; | |
namespace YieldExample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var stopwatch = new Stopwatch(); | |
Console.WriteLine("With yield:"); | |
stopwatch.Start(); | |
foreach (var randomNumber in GetRandomNumbers(200)) | |
{ | |
Console.WriteLine("Random number = " +randomNumber); | |
Console.WriteLine("Time so far = " +stopwatch.ElapsedMilliseconds); | |
} | |
stopwatch.Stop(); | |
var yeildLoopTotalTime = stopwatch.ElapsedMilliseconds; | |
Console.WriteLine(); | |
Console.WriteLine("With list"); | |
Console.WriteLine("BTW I'm doing work.. honest"); | |
stopwatch.Reset(); | |
stopwatch.Start(); | |
foreach (var randomNumber in GetRandomNumberList(200)) | |
{ | |
Console.WriteLine("Random number = " + randomNumber); | |
Console.WriteLine("Time so far = " + stopwatch.ElapsedMilliseconds); | |
} | |
stopwatch.Stop(); | |
var listLoopTotalTime = stopwatch.ElapsedMilliseconds; | |
Console.WriteLine(); | |
Console.WriteLine("Total time:"); | |
Console.WriteLine("Yield : " + yeildLoopTotalTime); | |
Console.WriteLine("List : " + listLoopTotalTime); | |
Console.Read(); | |
} | |
public static IEnumerable<int> GetRandomNumbers(int maxCount) | |
{ | |
var rand = new Random(); | |
for (int i = 0; i < maxCount; i++) | |
{ | |
Thread.Sleep(500); | |
yield return rand.Next(); | |
} | |
} | |
public static IList<int> GetRandomNumberList(int maxCount) | |
{ | |
var numberList = new List<int>(); | |
var rand = new Random(); | |
for (int i = 0; i < maxCount; i++) | |
{ | |
Thread.Sleep(500); | |
numberList.Add(rand.Next()); | |
} | |
return numberList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment