StackTrace构造函数和获取方法名称导致的性能影响

时间:2015-11-04 17:35:54

标签: c# performance perfview

我在日志记录库中有这段代码

var stackTrace = new StackTrace();
string operationName = stackTrace.GetFrame(1).GetMethod().Name;

根据我使用PerfView工具的性能分析,它显示为

Picture from PerfView etl file

有没有人知道我添加的代码对性能的影响? 如果是,是否有任何其他方式可以获得方法名称而不会产生更大的性能影响?

我目前在4核机器上运行1000 TPS。我发现它占用了我CPU的15.1%

1 个答案:

答案 0 :(得分:4)

从C#5开始,使用[CallerMemberName]

肯定更好地让编译器将其烘焙到调用网站中
public void Log(string message, [CallerMemberName] caller = null)
{
}

然后:

public void DoSomething()
{
    logger.Log("A message");
}

...由C#编译器转换为

public void DoSomething()
{
    logger.Log("A message", "DoSomething");
}