How much overhead does using MiniProfiler's Step() IDisposable add?
Asked Answered
S

1

6

I'd like to use MiniProfiler from time to time to profile my code, but I don't want to branch off and keep re-introducing it; I'd like to leave it in there and just remove the @MiniProfiler.RenderIncludes() call from my layout template when I'm not using it. However, my code would still look like this:

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...
}

How much overhead would leaving those Steps in there and disposing them cause? Is there a way to tell MiniProfiler I'm not using it so that Step basically does nothing, but I can still leave it in my code?

Stalinist answered 30/4, 2013 at 8:58 Comment(0)
B
8

As long as your MiniProfiler instance is null (i.e. you never call MiniProfiler.Start()), the Step() extension method will return null. The only overhead at this point is the using statement, which is negligible. Think of it as an extra if (false) statement that has to execute.

I would advise against the syntax you're using where you store the IDispoable outside of a using block, because you don't get automatic null checking on the .Dispose() call, e.g.

_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();
}

The way I usually work is to only profile once per method - if I need another step, I have to extract the code into another method, e.g.

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...
    }
}

This has the added benefit of keeping my methods small :)

If you're on .NET 4.5, you can take advantage of the CallerFilePathAttribute and use this .StepHere() helper method I put into our Stack Overflow code, which avoids having to name every Step() call!

Brunelle answered 30/4, 2013 at 19:39 Comment(2)
"I would advise against the syntax you're using where you store the IDispoable outside of a using block, because you don't get automatic null checking on the .Dispose() call" ... which is why I actually use a DisposeIfNotNull() extension method I created. The example just uses the standard method. :-)Stalinist
In a couple of places in our views, we actually do pass around the Step... I'll have to add that extension method, good idea!Brunelle

© 2022 - 2024 — McMap. All rights reserved.