复制代码 代码如下:
namespace ReflectionOptimization
{
public sealed class TestObject
{
public int Add(int a, int b)
{
// 简单演示
return a + b;
}
}
}
复制代码 代码如下:
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;
}
复制代码 代码如下:
var obj = new TestObject();
var add = obj.GetType().GetMethod("Add");
for (var i = 0; i < _TIMES; i++) add.Invoke(obj, new object[] {a, b});
复制代码 代码如下:
dynamic obj = new TestObject();
// 有木有发现这个代码超级简单?
for (var i = 0; i < _TIMES; i++) obj.Add(a, b);
复制代码 代码如下:
// 委托
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);
Debug模式:
调用方式第一次第二次第三次第四次第五次
Generic Call1.0224251.0128850.9907751.0209501.046880
Reflection147.489220146.012010142.690080139.189335141.663475
dynamic9.6458509.9799659.3072359.5326659.730030
Func1.2018601.2148001.1702151.1892801.239485
Delegate1.0622151.0616351.0675101.0471801.075190
Release模式:
调用方式第一次第二次第三次第四次第五次
Generic Call0.7456000.7413650.7221450.7326300.725645
Reflection141.778260142.855410142.346095139.649990138.541285
dynamic9.63146010.3418509.2842309.4575809.060470
Func0.8821000.8526800.8756950.8546550.831670
Delegate0.7102800.7224650.7233550.7271750.693320
点评&结论:
新闻热点
疑难解答
图片精选