![](/img/trans.png)
[英]CallerInfo, get name of variable passed to method (like nameof)
[英]Getting the caller method name - Reflection and CallerInfo attribute
刚刚基准化了使用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);
}
}
您必须在第二个循环之前重置计时器。 sw.Start
从第一次循环后的状态启动Stopwatch
,因此第二个结果实际上是将StackTrace和基于属性的解决方案加在一起的时间。
CallerMethodName
是编译类型的功能,它绝对应该更快。
使用来自您的结果的CallerMethodName
固定代码计时是:
21.7074064-(9.48074760000001 * 2)= 2.7459111999999806
那要快得多,不是吗?
第一次减去两次:一次是因为缺少Reset
调用,一次是因为+=
而不是=
。
更新
这些结果似乎太大了。 您确定使用从Visual Studio外部运行的Release版本吗? 我认为不会,因为否则您会得到完全相同的结果:永远不会使用callerName
并且可能会将其优化为无操作(至少在第二种情况下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.