Jez*_*Jez 5 performance mvc-mini-profiler
我想不时使用MiniProfiler来分析我的代码,但我不想分支并继续重新引入它; 我想把它留在那里,@MiniProfiler.RenderIncludes()当我不使用它时,只是从我的布局模板中删除调用.但是,我的代码仍然如下所示:
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...
}
Run Code Online (Sandbox Code Playgroud)
将这些Steps留在那里并处理它们需要多少开销?有没有办法告诉MiniProfiler我没有使用它,所以Step基本上什么也没做,但我仍然可以把它留在我的代码中?
只要您的MiniProfiler实例为null(即您从不调用MiniProfiler.Start()),Step()扩展方法将返回null.此时唯一的开销是using声明,这可以忽略不计.将其视为if (false)必须执行的额外声明.
我会建议您使用存储块IDispoable外部的语法using,因为您没有对.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();
}
Run Code Online (Sandbox Code Playgroud)
我通常的工作方式是每个方法只配置一次 - 如果我需要另一个步骤,我必须将代码提取到另一个方法,例如
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...
}
}
Run Code Online (Sandbox Code Playgroud)
这有一个额外的好处,保持我的方法小:)
如果你在.NET 4.5,你可以利用的优势CallerFilePathAttribute,并使用这个.StepHere()辅助方法,我把我们的堆栈溢出代码,它避免了命名每一个Step()来电!