问题
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