2013-04-30 51 views
4

我想不時使用MiniProfiler來剖析我的代碼,但我不想分支並不斷重新介紹它;我想將它留在那裏,並在我不使用時從我的佈局模板中刪除@MiniProfiler.RenderIncludes()呼叫。然而,我的代碼仍然是這樣的:使用MiniProfiler的Step()IDisposable添加有多少開銷?

using (MiniProfiler.Current.Step("Generate events index view model")) { 
    _thisStep = MiniProfiler.Current.Step("Check query string"); 
    int pageIndex = 0; 
    // Do check... 
    _thisStep.Dispose(); 

    // Do other stuff... 
} 

在多少開銷將離開這些Step那兒和處理它們引起?有沒有辦法告訴MiniProfiler我沒有使用它,所以Step基本上什麼都不做,但我仍然可以將它留在我的代碼?

回答

7

只要您的MiniProfiler實例爲空(即您永遠不會調用MiniProfiler.Start()),Step()擴展方法將返回空值。此時唯一的開銷是using聲明,這是微不足道的。把它看作是必須執行的額外if (false)聲明。

我會建議對你使用,你存儲IDispoableusing塊的語法,因爲你沒有得到自動空檢查在.Dispose()調用,例如

_thisStep = MiniProfiler.Current.Step("Check query string"); 

// if you do it this way, you will have to manually check for null every time 
if (_thisStep != null) { 
    _thisStep.Dispose(); 
} 

我平時工作是每方法僅輪廓一次的方式 - 如果我需要另一步驟中,我必須的代碼提取到的另一種方法,例如

public EventsIndexViewModel GetViewModel() 
{ 
    using (MiniProfiler.Current.Step("Generate events index view model")) 
    { 
     var pageIndex = GetPageIndex(); 
    } 
} 

private int GetPageIndex() 
{ 
    using (MiniProfiler.Current.Step("GetPageIndex")) 
    { 
     // Do check... return result... 
    } 
} 

這有讓我的小方法:)

如果你在.NET 4.5,你可以採取CallerFilePathAttribute的優勢,使用this .StepHere() helper method我把我們的堆棧溢出代碼的好處,這避免了每個Step()電話的名字!

+0

「我建議您不要在使用塊的外部存儲IDispoable的地方使用語法,因爲您不會在.Dispose()調用中自動進行空值檢查」......這就是爲什麼我實際上使用我創建的DisposeIfNotNull()擴展方法。該示例僅使用標準方法。 :-) – Jez 2013-05-01 08:41:54

+0

在我們的觀點中的幾個地方,我們確實會傳遞步驟......我將不得不添加該擴展方法,這是個好主意! – 2013-05-01 17:02:50