Skip to content

Instantly share code, notes, and snippets.

@david-mclean
Last active December 15, 2015 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-mclean/5228693 to your computer and use it in GitHub Desktop.
Save david-mclean/5228693 to your computer and use it in GitHub Desktop.
Use yield to return a few items from an iterator.
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