Skip to content

Instantly share code, notes, and snippets.

@Kimserey
Created June 30, 2017 02:18
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 Kimserey/ac593675ee038b4978cee9d7cdb0f666 to your computer and use it in GitHub Desktop.
Save Kimserey/ac593675ee038b4978cee9d7cdb0f666 to your computer and use it in GitHub Desktop.
Distinct.Any
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace DistinctAny
{
class Program
{
static void Main(string[] args)
{
var evaluation = "A";
var stw = Stopwatch.StartNew();
Console.WriteLine("Start Y1");
var y1 = new[] { "A", "A", "A", "A", "B" }
.Any(i =>
{
Thread.Sleep(1000);
return i == evaluation;
});
Console.WriteLine("Y1 completed {0}", stw.ElapsedMilliseconds);
stw.Restart();
Console.WriteLine("Start Y2");
var y2 = new[] { "A", "A", "A", "A", "B" }
.Distinct()
.Any(i =>
{
Thread.Sleep(1000);
return i == evaluation;
});
Console.WriteLine("Y2 completed {0}", stw.ElapsedMilliseconds);
Console.ReadKey();
}
}
}
@aft-ape
Copy link

aft-ape commented Jun 30, 2017

        static void Main(string[] args)
        {
            var testData = Enumerable.Range(1, 10000000)
                .Append(0);

            long initialMemory = GC.GetTotalMemory(false);

            Console.WriteLine("Without Distinct");
            var stw = Stopwatch.StartNew();
            var y1 = testData.Any(i => i == 0);
            stw.Stop();
            long step1Memory = GC.GetTotalMemory(false);
            Console.WriteLine("Y1 completed {0}ms", stw.ElapsedMilliseconds);
            Console.WriteLine("Memory increase {0}kB", (step1Memory - initialMemory)/1024);

            Console.WriteLine("----------");
            Console.WriteLine("With Distinct");
            stw.Restart();
            var y2 = testData.Distinct().Any(i => i == 0);
            stw.Stop();
            long step2Memory = GC.GetTotalMemory(false);
            Console.WriteLine("Y2 completed {0}ms", stw.ElapsedMilliseconds);
            Console.WriteLine("Memory increase {0}kB", (step2Memory - step1Memory)/1024);

            Console.ReadKey();
        }

Output:

Without Distinct
Y1 completed 399ms
Memory increase 8kB
----------
With Distinct
Y2 completed 994ms
Memory increase 458688kB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment