由于 StackTrace 构造函数和获取方法名称而导致的性能影响 [英] Performance impact due to StackTrace constructor and getting method name

查看:64
本文介绍了由于 StackTrace 构造函数和获取方法名称而导致的性能影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的日志库中有这段代码

I have this piece of code in our logging library

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

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

And as per my performance analysis using the PerfView Tool it shows up as

有谁知道我添加的代码对性能的影响?如果是,有没有其他方法可以在不影响性能的情况下获取方法名称?

Does anyone know of the performance implications by the code that i have added? If yes is there any other way that i can get method name without having greater performance impact?

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

I am currently running it as 1000 TPS on a 4 core machine. And i see that the it uses 15.1% of my CPU

推荐答案

从 C# 5 开始,肯定让编译器将其烘焙到调用站点中会更好,而是使用 [CallerMemberName]

As of C# 5, it would definitely be better to get the compiler to bake this into the call site instead, using [CallerMemberName]

public void Log(string message, [CallerMemberName] caller = null)
{
}

那么:

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

... 被 C# 编译器转换成

... is converted by the C# compiler into

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

这篇关于由于 StackTrace 构造函数和获取方法名称而导致的性能影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆