3

我的日志库中有这段代码

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

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

图片来自 PerfView etl 文件

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

我目前在 4 核机器上以 1000 TPS 运行它。而且我看到它使用了我的 CPU 的 15.1%

4

1 回答 1

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");
}
于 2015-11-04T17:39:40.810 回答