Skip to content

Instantly share code, notes, and snippets.

@wipiano
Created July 29, 2017 08:15
Show Gist options
  • Save wipiano/f2ab3aaedd50817f5e926e72d4e81b03 to your computer and use it in GitHub Desktop.
Save wipiano/f2ab3aaedd50817f5e926e72d4e81b03 to your computer and use it in GitHub Desktop.
HashSet に対する Except と Where の性能比較
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ExceptVsWhere
{
class Program
{
static void Main(string[] args)
{
// 要素数を変えて試してみる
var lengths = new int[] {10, 100, 1000, 10000, 100000, 1000000, 10000000};
#if NETCOREAPP1_1
Console.WriteLine(".NET Core 1.1");
#elif NET461
Console.WriteLine(".NET Framework 4.6.1");
#endif
Console.WriteLine("Length ,Except ,Where");
foreach (var length in lengths)
{
(long except, long where) = Test(length);
Console.WriteLine($"{length:D8},{except:D7},{where:D7}");
}
}
private static (long exceptMilliSec, long whereMilliSec) Test(int length)
{
// 10 回やる
const int loop = 10;
var first = Enumerable.Range(1, length * 2);
var second = new HashSet<int>(Enumerable.Range(1, length));
// except
var exceptSw = new Stopwatch();
exceptSw.Start();
Repeat(() => first.Except(second).ToArray(), loop);
exceptSw.Stop();
// where
var whereSw = new Stopwatch();
whereSw.Start();
Repeat(() => first.Where(x => second.Contains(x)).ToArray(), loop);
whereSw.Stop();
return (exceptSw.ElapsedMilliseconds, whereSw.ElapsedMilliseconds);
}
private static void Repeat(Action action, int count)
{
for (var i = 0; i < count; i++)
{
action();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment