Friday, July 22, 2011

Generic Method With Func

static void Main(string[] args)
{
List strs = CreateStrings();
bool result;
Console.WriteLine("Use ImplementByToUpper");
Func sdy=s => ImplementByToUpper(strs, s);
// result = MeasurePerformance(s => ImplementByToUpper(strs, s), "yZh", 1000);
result = MeasurePerformance(sdy, "yZh", 1000);
Console.WriteLine("result is " + result.ToString());
Console.ReadLine();


}
private static TResult MeasurePerformance(Func func, TArg arg, int loop)
{
GC.Collect();
int gc0 = GC.CollectionCount(0);
int gc1 = GC.CollectionCount(1);
int gc2 = GC.CollectionCount(2);
TResult result = default(TResult);
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < loop; i++)
{
result = func(arg);
}
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + "ms");
Console.WriteLine("GC 0:" + (GC.CollectionCount(0) - gc0).ToString());
Console.WriteLine("GC 1:" + (GC.CollectionCount(1) - gc1).ToString());
Console.WriteLine("GC 2:" + (GC.CollectionCount(2) - gc2).ToString());
return result;
}


private static bool ImplementByToUpper(List strs, string value)
{
for (int i = 0; i < strs.Count; i++)
if (value.ToUpper() == strs[i].ToUpper())
return true;
return false;
}

private static List CreateStrings()
{
List strs = new List(10000);
char[] chs = new char[3];
for (int i = 0; i < 10000; i++)
{
int j = i;
for (int k = 0; k < chs.Length; k++)
{
chs[k] = (char)('a' + j % 26);
j = j / 26;
}
strs.Add(new string(chs));
}
return strs;
}

0 Comments:

Post a Comment

<< Home