Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Created April 13, 2015 16:56
Show Gist options
  • Save fearthecowboy/e3148a3c7d79ab8e5a13 to your computer and use it in GitHub Desktop.
Save fearthecowboy/e3148a3c7d79ab8e5a13 to your computer and use it in GitHub Desktop.
Show how ToArray() with Distinct isn't good
void Main()
{
Console.WriteLine("\r\n==== Distinct() without ToArray()====");
var stopwatch = Stopwatch.StartNew();
var results = Results().Distinct();
ProcessResults(results,stopwatch);
Console.WriteLine("\r\n==== Distinct() with ToArray()====");
stopwatch = Stopwatch.StartNew();
results = Results().ToArray().Distinct();
ProcessResults(results, stopwatch);
}
public void ProcessResults(IEnumerable<string> results, Stopwatch stopWatch) {
var first = true;
foreach( var item in results) {
if( first) {
first = false;
Console.WriteLine("Time to first item: {0} ms", stopWatch.ElapsedMilliseconds );
}
Console.WriteLine("{0}ms :: '{1}' ", stopWatch.ElapsedMilliseconds , item);
}
Console.WriteLine("Total Time to enumerate whole set: {0} ms", stopWatch.ElapsedMilliseconds );
}
public IEnumerable<string> Results() {
yield return "One";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Two";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Three";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Four";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Five";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Six";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "Seven";
System.Threading.Thread.Sleep(100); // each item takes a bit of time.
yield return "One";
}
/** RESULTS:
==== Distinct() without ToArray()====
Time to first item: 1 ms
1ms :: 'One'
102ms :: 'Two'
203ms :: 'Three'
303ms :: 'Four'
403ms :: 'Five'
504ms :: 'Six'
605ms :: 'Seven'
Total Time to enumerate whole set: 706 ms
==== Distinct() with ToArray()====
Time to first item: 703 ms
703ms :: 'One'
703ms :: 'Two'
703ms :: 'Three'
703ms :: 'Four'
703ms :: 'Five'
703ms :: 'Six'
703ms :: 'Seven'
Total Time to enumerate whole set: 703 ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment