我已经编写了一个日志类和一个函数,如以下代码所示:
Log(System.Reflection.MethodBase methodBase, string message)每次我记录一些东西时,我也会记录来自methodBase.Name和methodBase.DeclaringType.Name的类名。
我读了下面的帖子Using Get CurrentMethod,我注意到这个方法很慢。
我应该使用this.GetType()而不是System.Reflection.MethodBase,还是应该在我的日志中手动记录类/方法名,例如Log("ClassName.MethodName","log message)?最佳实践是什么?
发布于 2011-02-03 20:46:14
这真的要看情况。
如果您使用this.GetType()方法,您将丢失方法信息,但您将获得很大的性能增益(根据您的链接,显然是1200倍)。
如果你提供一个让调用者提供字符串的接口(例如Log("ClassName.MethodName", "log message") ),你可能会获得更好的性能,但这会使你的应用编程接口不那么友好(调用开发人员必须提供类名和方法名)。
发布于 2013-06-21 00:54:42
我知道这是一个古老的问题,但我想我应该抛出一个简单的解决方案,它看起来性能很好,并维护了符号
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);
}
}运行这段代码会得到以下结果:
Reflection Time: 1692.1692ms
Lookup Time: 19.0019ms
Press Enter to exit对于一百万次迭代来说,这并不是什么坏事,特别是与直接的反射相比。方法组被转换为Delegate类型,您将一直维护一个符号链接到日志记录中。没有可笑的魔法弦。
https://stackoverflow.com/questions/4885582
复制相似问题