SYSK 394: Cost of getting StackTrace and finding a StackFrame

I wanted to find out the overhead of getting the stack trace and finding a specific method in the array of stack frames.  The profiled code looked like this:

private static MethodBase GetCallerMethod(string caller)


    StackTrace st = new StackTrace(2);

    return (from f in st.GetFrames() let m = f.GetMethod() where m.Name == caller select m).FirstOrDefault();



I used QueryThreadCycleTime API or more precise measurements


[return: MarshalAs(UnmanagedType.Bool)]

static extern bool QueryThreadCycleTime(IntPtr ThreadHandle, out ulong CycleTime);


static extern IntPtr GetCurrentThread();


and here is what I found out for my test case:

  • Average CPU cycles to get StackFrame[]:  ~500,000
  • Average CPU cycles for Linq query to find the calling method (which is usually near the top of the stack): ~70,000
  • In comparison, a call to a local SQL server database to execute a stored procedure (getting a record based on primary key) on a very small database (narrow, well indexed tables with < 100 rows):  ~910,000

In summary, based on my tests, the cost of finding a stack frame is in the same ballpark as making a stored procedure call on a very small (sample) well indexed database residing on the same machine.