Ioa*_*nis 9 c# reflection performance methodbase
我编写了一个日志类和一个函数,如下面的代码所示:
Log(System.Reflection.MethodBase methodBase, string message)
Run Code Online (Sandbox Code Playgroud)
每次我记录某些东西时,我也会从methodBase.Name和methodBase.DeclaringType.Name中记录类名.
我阅读了以下文章使用Get CurrentMethod,我注意到这个方法很慢.
我应该使用this.GetType()而不是System.Reflection.MethodBase,或者我应该在我的日志中手动记录类/方法名称,例如Log("ClassName.MethodName","log message")?最佳做法是什么?
这真的取决于.
如果您使用该this.GetType()方法,您将丢失方法信息,但您将获得很大的性能提升(根据您的链接显然是1200倍).
如果你提供一个允许调用者提供字符串的接口(例如Log("ClassName.MethodName", "log message"),你可能会获得更好的性能,但这会使你的API不那么友好(调用开发人员必须提供类名和方法名).
我知道这是一个古老的问题,但是我认为我会抛出一个简单的解决方案,该解决方案似乎运行良好并维护符号
static void Main(string[] args)
{
int loopCount = 1000000; // 1,000,000 (one million) iterations
var timer = new Timer();
timer.Restart();
for (int i = 0; i < loopCount; i++)
Log(MethodBase.GetCurrentMethod(), "whee");
TimeSpan reflectionRunTime = timer.CalculateTime();
timer.Restart();
for (int i = 0; i < loopCount; i++)
Log((Action<string[]>)Main, "whee");
TimeSpan lookupRunTime = timer.CalculateTime();
Console.WriteLine("Reflection Time: {0}ms", reflectionRunTime.TotalMilliseconds);
Console.WriteLine(" Lookup Time: {0}ms", lookupRunTime.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
public static void Log(Delegate info, string message)
{
// do stuff
}
public static void Log(MethodBase info, string message)
{
// do stuff
}
public class Timer
{
private DateTime _startTime;
public void Restart()
{
_startTime = DateTime.Now;
}
public TimeSpan CalculateTime()
{
return DateTime.Now.Subtract(_startTime);
}
}
Run Code Online (Sandbox Code Playgroud)
运行这段代码给我以下结果:
Reflection Time: 1692.1692ms
Lookup Time: 19.0019ms
Press Enter to exit
Run Code Online (Sandbox Code Playgroud)
一百万次迭代,这不是坏事,在所有的,特别是相对于直线上升的反映。方法组被强制转换为Delegate类型,您将在整个记录过程中维护一个符号链接。没有愚蠢的魔术弦。
| 归档时间: |
|
| 查看次数: |
11532 次 |
| 最近记录: |