【发布时间】:2014-04-08 06:49:34
【问题描述】:
刚刚对使用StackTrace 和CallerInfo Attributes 的性能进行了基准测试。
令人震惊的是,我发现使用StackTrace 的速度要快得多,尽管我在每个地方都看到To get the caller method name, the preferred approach is CallerInfo attributes。
public class Program
{
public static void Main(string[] args)
{
Method1();
}
static void Method1([CallerMemberName]string memberName = "")
{
double stackTraceTimings = 0;
var sw = new Stopwatch();
foreach(var item in Enumerable.Range(1,1000).ToList())
{
sw.Start();
var callerName = new StackFrame(1).GetMethod().Name;
sw.Stop();
stackTraceTimings += sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Elapsed Time for retrieving the caller name using StackFrame in 1000 iterations ={0}",stackTraceTimings/1000);
stackTraceTimings = 0;
foreach(var item in Enumerable.Range(1,1000).ToList())
{
sw.Start();
var callerName = (memberName);
sw.Stop();
stackTraceTimings += sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Elapsed Time for retrieving the caller name using callerInfo Attribute in 1000 iterations ={0}",stackTraceTimings/1000);
}
输出: 在 1000 次迭代中使用 StackFrame 检索调用方名称的经过时间 =9.48074760000001
在 1000 次迭代中使用 callerInfo 属性检索来电者姓名所用的时间 =21.7074064
我是不是误会了什么?使用CallerInfo 属性是首选方法吧?
感谢以下答案的指出。
每次循环中我都必须重新启动计时器。
那么,谁赢了?正如下面的答案所说,@ 987654327@。因为,它是一个编译时特性,而且速度更快。
在 1000 次迭代中使用 StackFrame 检索调用方名称所用的时间 =0.00762619999999992
在 1000 次迭代中使用 callerInfo 属性检索来电者姓名所用的时间 =0.00639420000000002
我使用了下面的代码(修改后的),得到了上面的结果。
public class Program
{
public static void Main(string[] args)
{
Method1();
}
static void Method1([CallerMemberName]string memberName = "")
{
double stackTraceTimings = 0;
var sw = new Stopwatch();
foreach(var item in Enumerable.Range(1,1000).ToList())
{
sw.Start();
var callerName = new StackFrame(1).GetMethod().Name;
sw.Stop();
Console.Write(callerName);
sw.Restart();
stackTraceTimings += sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Elapsed Time for retrieving the caller name using StackFrame in 1000 iterations ={0}",stackTraceTimings/1000);
stackTraceTimings = 0;
foreach(var item in Enumerable.Range(1,1000).ToList())
{
sw.Start();
var callerName = (memberName);
Console.Write(callerName);
sw.Stop();
sw.Restart();
stackTraceTimings += sw.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Elapsed Time for retrieving the caller name using callerInfo Attribute in 1000 iterations ={0}",stackTraceTimings/1000);
}
}
【问题讨论】:
-
您是在调用 CallerMemberNameAttribute“callerInfo”吗?令人困惑。
标签: c# .net reflection .net-4.5 callermembername