Last active
July 29, 2017 10:28
-
-
Save wipiano/c3b52ff9981743b97a83e125b8acf1bc to your computer and use it in GitHub Desktop.
LINQ と foreach どっちが速い!? (Except)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
namespace LinqVsForEach | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// 要素数を変えて試してみる | |
var lengths = new int[] {10, 100, 1000, 10000, 100000, 1000000, 10000000, 50000000}; | |
#if NETCOREAPP1_1 | |
Console.WriteLine(".NET Core 1.1"); | |
#elif NET461 | |
Console.WriteLine(".NET Framework 4.6.1"); | |
#endif | |
Console.WriteLine("Length\toreore\tganbatta\tlinq"); | |
foreach (var length in lengths) | |
{ | |
(long oreore, long ganbatta, long linq) = Test(length); | |
Console.WriteLine($"{length}\t{oreore}\t{ganbatta}\t{linq}"); | |
} | |
} | |
private static (long oreoreMilliSec, long ganbattaMilliSec, long linqMilliSec) Test(int length) | |
{ | |
// 10 回やる | |
const int loop = 10; | |
var first = Enumerable.Range(1, length * 2); | |
var second = Enumerable.Range(1, length); | |
// オレオレ手抜き Except | |
// 遅すぎて無理。。。 | |
//var oreoreSw = new Stopwatch(); | |
//oreoreSw.Start(); | |
//Repeat(() => first.OreOreExcept(second).ToArray(), loop); | |
//oreoreSw.Stop(); | |
// オレオレがんばった Except | |
var ganbattaSw = new Stopwatch(); | |
ganbattaSw.Start(); | |
Repeat(() => first.OreOreGanbattaExcept(second).ToArray(), loop); | |
ganbattaSw.Stop(); | |
// LINQ の Except | |
var linqSw = new Stopwatch(); | |
linqSw.Start(); | |
Repeat(() => first.Except(second).ToArray(), loop); | |
linqSw.Stop(); | |
return (0, ganbattaSw.ElapsedMilliseconds, linqSw.ElapsedMilliseconds); | |
} | |
private static void Repeat(Action action, int count) | |
{ | |
for (var i = 0; i < count; i++) | |
{ | |
action(); | |
} | |
} | |
} | |
internal static class OreOreExtensions | |
{ | |
public static IEnumerable<T> OreOreExcept<T>(this IEnumerable<T> first, IEnumerable<T> second) | |
{ | |
foreach (var elem in first) | |
{ | |
foreach (var secondElem in second) | |
{ | |
if (elem.Equals(secondElem)) | |
{ | |
yield return elem; | |
break; | |
} | |
} | |
} | |
} | |
public static IEnumerable<T> OreOreGanbattaExcept<T>(this IEnumerable<T> first, IEnumerable<T> second) | |
{ | |
var set = new HashSet<T>(second); | |
foreach (var elem in first) | |
{ | |
if (set.Add(elem)) | |
{ | |
yield return elem; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment