Using GetCurrentMethod in (supposedly) high-performance code

前端 未结 3 1468
时光取名叫无心
时光取名叫无心 2021-01-18 14:03

For logging purposes, some methods in our application include the following line:

Dim Log As ILog = GetLog(Reflection.MethodBase.GetCurrentMethod().Declaring         


        
3条回答
  •  -上瘾入骨i
    2021-01-18 14:51

    I just had the same question and found this answer, but maybe it is not up to date any more so I post my testresults...

    I don't know about previous versions of the dot net Framework, but in dot net Framework 4 I get the following calling Times. So performance should not be an issue any more...

    • First Call to MethodBase.GetCurrentMethod().DeclaringType: 0 ms - 221 ticks
    • First Call to this.GetType(): 0 ms - 225 ticks

    Here is the code which produced this output:

            _txtReport.Text = string.Empty;
            var sw = new Stopwatch();
    
            sw.Start();
            var type = MethodBase.GetCurrentMethod().DeclaringType;
            sw.Stop();
    
            _txtReport.Text += string.Format("First Call to MethodBase.GetCurrentMethod().DeclaringType: {0} ms - {1} ticks{2}",
                                             sw.ElapsedMilliseconds, sw.ElapsedTicks, Environment.NewLine);
    
            sw.Start();
            var type1 = this.GetType();
            sw.Stop();
    
            _txtReport.Text += string.Format("First Call to this.GetType(): {0} ms - {1} ticks{2}",
                                             sw.ElapsedMilliseconds, sw.ElapsedTicks, Environment.NewLine);
    

提交回复
热议问题