Last active
December 15, 2015 08:09
-
-
Save david-mclean/5228693 to your computer and use it in GitHub Desktop.
Use yield to return a few items from an iterator.
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.Linq; | |
using System.Threading; | |
namespace YieldExample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
var yieldedRandoms = GetRandoms().Take(10); | |
stopwatch.Stop(); | |
var yeildLoopTotalTime = stopwatch.ElapsedMilliseconds; | |
Console.WriteLine(); | |
stopwatch.Reset(); | |
stopwatch.Start(); | |
var listedRandoms = GetRandomsList().Take(10); | |
stopwatch.Stop(); | |
var listLoopTotalTime = stopwatch.ElapsedMilliseconds; | |
Console.WriteLine("Total time:"); | |
Console.WriteLine("Yield : " + yeildLoopTotalTime); | |
Console.WriteLine("List : " + listLoopTotalTime); | |
Console.Read(); | |
} | |
public static IEnumerable<int> GetRandoms() | |
{ | |
var rand = new Random(); | |
for (int i = 0; i < 5000000; i++) | |
{ | |
yield return rand.Next(); | |
} | |
} | |
public static IList<int> GetRandomsList() | |
{ | |
var numberList = new List<int>(); | |
var rand = new Random(); | |
for (int i = 0; i < 5000000; i++) | |
{ | |
numberList.Add(rand.Next()); | |
} | |
return numberList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment