1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| class Program
{
static void Main(string[] args)
{
List<string> s = new List<string> { "aaa", "aab", "ccc" };
Func<string, string> mySelector = new Func<string, string>(y => y);
System.Linq.Enumerable.Select(s, mySelector);
string result;
var test1 = s.Select2(mySelector);
var test2 = s.Select3(mySelector);
Stopwatch sw = new Stopwatch();
for (int i = 0; i < 20; i++)
{
sw.Reset();
sw.Start();
foreach (string item in test1)
{
result = item;
}
sw.Stop();
Console.WriteLine("Select2 : iteration {0} {1} ticks", i, sw.ElapsedTicks);
}
for (int i = 0; i < 20; i++)
{
sw.Reset();
sw.Start();
foreach (string item in test2)
{
result = item;
}
sw.Stop();
Console.WriteLine("Select3 : iteration {0} {1} ticks", i, sw.ElapsedTicks);
}
}
}
public static class Extensions
{
public static IEnumerable<TResult> Select2<T, TResult>(this IEnumerable<T> en, Func<T, TResult> selector)
{
foreach (var item in en)
yield return selector(item);
}
public static IEnumerable<TResult> Select3<T, TResult>(this IEnumerable<T> en, Func<T, TResult> selector)
{
return en.Select(selector);
}
} |
Partager