Performance impact due to StackTrace constructor and getting method name

时间秒杀一切 提交于 2019-12-10 19:06:20

问题


I have this piece of code in our logging library

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

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?

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


回答1:


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)
{
}

Then:

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

... is converted by the C# compiler into

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


来源:https://stackoverflow.com/questions/33528415/performance-impact-due-to-stacktrace-constructor-and-getting-method-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!