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
属性是首选方法吗?
感谢以下答案的指出。
每次循环中我都必须重新启动计时器。
那么,谁赢了?正如下面的答案所说,CallerInfo
。因为,它是一个编译时特性并且速度更快。
在 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);
}
}