您好我調查創建的CacheDependency對象的性能損失,所以我寫了一個很簡單的測試程序如下:性能委託和方法組
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Caching;
namespace Test
{
internal class Program
{
private static readonly string[] keys = new[] {"Abc"};
private static readonly int MaxIteration = 10000000;
private static void Main(string[] args)
{
Debug.Print("first set");
test7();
test6();
test5();
test4();
test3();
test2();
Debug.Print("second set");
test2();
test3();
test4();
test5();
test6();
test7();
}
private static void test2()
{
DateTime start = DateTime.Now;
var list = new List<CacheDependency>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(new CacheDependency(null, keys));
}
Debug.Print("test2 Time: " + (DateTime.Now - start));
}
private static void test3()
{
DateTime start = DateTime.Now;
var list = new List<Func<CacheDependency>>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(() => new CacheDependency(null, keys));
}
Debug.Print("test3 Time: " + (DateTime.Now - start));
}
private static void test4()
{
var p = new Program();
DateTime start = DateTime.Now;
var list = new List<Func<CacheDependency>>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(p.GetDep);
}
Debug.Print("test4 Time: " + (DateTime.Now - start));
}
private static void test5()
{
var p = new Program();
DateTime start = DateTime.Now;
var list = new List<Func<CacheDependency>>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(() => { return p.GetDep(); });
}
Debug.Print("test5 Time: " + (DateTime.Now - start));
}
private static void test6()
{
DateTime start = DateTime.Now;
var list = new List<Func<CacheDependency>>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(GetDepSatic);
}
Debug.Print("test6 Time: " + (DateTime.Now - start));
}
private static void test7()
{
DateTime start = DateTime.Now;
var list = new List<Func<CacheDependency>>();
for (int i = 0; i < MaxIteration; i++)
{
list.Add(() => { return GetDepSatic(); });
}
Debug.Print("test7 Time: " + (DateTime.Now - start));
}
private CacheDependency GetDep()
{
return new CacheDependency(null, keys);
}
private static CacheDependency GetDepSatic()
{
return new CacheDependency(null, keys);
}
}
}
但我不明白爲什麼這些結果看起來像這樣的:
first set
test7 Time: 00:00:00.4840277
test6 Time: 00:00:02.2041261
test5 Time: 00:00:00.1910109
test4 Time: 00:00:03.1401796
test3 Time: 00:00:00.1820105
test2 Time: 00:00:08.5394884
second set
test2 Time: 00:00:07.7324423
test3 Time: 00:00:00.1830105
test4 Time: 00:00:02.3561347
test5 Time: 00:00:00.1750100
test6 Time: 00:00:03.2941884
test7 Time: 00:00:00.1850106
特別是:
- 爲什麼TEST4和TEST6慢得多 比他們的代表版本?我也 注意到Resharper特別是 有一個評論代表 版本建議改變test5和 test7「祕密方法組」。 與test4和test6 相同,但它們實際上比較慢?
- 我在調用 test4和test6時,應該不是靜態的 調用始終更快,我似乎沒有一致的 性能差異?