Skip to content

Instantly share code, notes, and snippets.

@david-mclean
Created March 23, 2013 16:29
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/5228317 to your computer and use it in GitHub Desktop.
Save david-mclean/5228317 to your computer and use it in GitHub Desktop.
An example of using yield.
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