Created
January 23, 2014 13:08
-
-
Save lacolaco/8578182 to your computer and use it in GitHub Desktop.
IE<T>#Random() Performance test
This file contains hidden or 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; | |
using System.Text; | |
namespace RandomPerformance | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var sw = new Stopwatch(); | |
//IE<int> | |
var sample1 = Enumerable.Repeat(0, 100000); | |
//配列 | |
var sample2 = sample1.ToArray(); | |
//List | |
var sample3 = sample1.ToList(); | |
var samples = new IEnumerable<int>[] { sample1, sample2, sample3 }; | |
foreach(var i in Enumerable.Range(0, 3)) | |
{ | |
Console.WriteLine("----sample: " + SampleName(i) + "----"); | |
Console.WriteLine("--OrderBy--"); | |
sw.Restart(); | |
foreach(var _ in Enumerable.Range(0, 1000)) | |
{ | |
RandomOrderBy(samples[i]); | |
} | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
Console.WriteLine("--ElementAt--"); | |
sw.Restart(); | |
foreach(var _ in Enumerable.Range(0, 1000)) | |
{ | |
RandomElementAt(samples[i]); | |
} | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
Console.WriteLine("--Skip--"); | |
sw.Restart(); | |
foreach(var _ in Enumerable.Range(0, 1000)) | |
{ | |
RandomSkip(samples[i]); | |
} | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
} | |
Console.ReadLine(); | |
} | |
static Random _Rand = new Random(); | |
static T RandomOrderBy<T>(IEnumerable<T> ie) | |
{ | |
return ie.OrderBy(x => _Rand.Next()).First(); | |
} | |
static T RandomElementAt<T>(IEnumerable<T> ie) | |
{ | |
return ie.ElementAt(_Rand.Next(ie.Count())); | |
} | |
static T RandomSkip<T>(IEnumerable<T> ie) | |
{ | |
return ie.Skip(_Rand.Next(ie.Count())).First(); | |
} | |
static string SampleName(int i) | |
{ | |
if(i == 0) return "IEnumerable<T>"; | |
else if(i == 1) return "Array<T>"; | |
else return "List<T>"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment