使用委託優化反射

1. delegatespa

// 委託
public delegate int AddMethod(int a, int b);

// 實現
var obj = new TestObject();
var objType = obj.GetType();
var add = objType.GetMethod("Add");
var d = (AddMethod)Delegate.CreateDelegate(typeof(AddMethod), obj, add);

for (var i = 0; i < _TIMES; i++) d(a, b);

2. funcpwa

var d = (Func<TestObject, int, int, int>)Delegate.CreateDelegate(typeof(Func<TestObject, int, int, int>), add);

3. reflectioncode

 var obj = new TestObject();
 var add = obj.GetType().GetMethod("Add");
 
 for (var i = 0; i < _TIMES; i++) add.Invoke(obj, new object[] {a, b});

4. Testblog

 

private static double _Run(string description, Action<int, int> action, int a, int b)
{
if (action == null) throw new ArgumentNullException("action");

// 啓動計時器
var stopwatch = Stopwatch.StartNew();

// 運行要測量的代碼
action(a, b);

// 終止計時
stopwatch.Stop();

// 輸出結果
Console.WriteLine("{0}: {1}", description, stopwatch.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture));

// 返回執行時間
return stopwatch.Elapsed.TotalMilliseconds;
}
相關文章
相關標籤/搜索