Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Nate 143 posts 184 karma points
    Nov 25, 2011 @ 19:01

    Help me speed up this razor macro

    This macro builds my navigation.  It takes 2-3 seconds to run.  I have it cached, but I'd like it to go faster on first run.


    var ulClass = String.IsNullOrEmpty(Parameter.UlClass) ? "" : String.Format(" class=\"{0}\"", Parameter.UlClass); 
        var ulID = String.IsNullOrEmpty(Parameter.UlID) ? "" : String.Format(" id=\"{0}\"", Parameter.UlID); 
        var selectionCriteria = String.IsNullOrEmpty(Parameter.Selection) ? "" : Parameter.Selection;
                @foreach (var item in Model.AncestorOrSelf().Descendants().Where("Level <= 3 && " + @Html.Raw(selectionCriteria) + " == true").OrderBy("level, sortOrder"))
                    var selected = Array.IndexOf(Model.Path.Split(','), item.Id.ToString()) >= 0 ? " class=\"selected\"" : "";
                        <a@Html.Raw(selected) href="@item.Url">@item.Name.ToUpper()</a>

    Here's the offending line:

    Model.AncestorOrSelf().Descendants().Where("Level <= 3 && " + @Html.Raw(selectionCriteria) + " == true").OrderBy("level, sortOrder"))

    I have navigation elements that are 2 levels down from my root.  I have around 650 nodes total.  I think this query is looking through all the elements and not just looking through the first few levels.

    I'd like to restrict the query to only look for the first <= 3 levels, then apply the where clause.  I've tried Decendants(3) but that didn't work.

    Any ideas how I speed this up?


  • Jonas Eriksson 930 posts 1825 karma points
    Nov 25, 2011 @ 21:29
    Jonas Eriksson


    so you like to return _all_ nodes from level 1,2 and 3 which fulfills the condition selectionCriteria?

    just an idea, I havent tried it myself but this should limit the loop a bit, especially if the most nodes are on level 4 and below:

    @foreach(var item inModel.AncestorOrSelf().Descendants(n=>n.Level<=3).Where(@Html.Raw(selectionCriteria)+" == true").OrderBy("level, sortOrder"))

    .Descendants(3) returns Descendants(n=>n.Level>=3) ref


  • Nate 143 posts 184 karma points
    Nov 26, 2011 @ 19:14

    I get "Expresions cannot contain labmda expressions".

    In the mean time I hard coded the nav.  Now it takes 5ms :).  I might just keep it that way.  I would like to know how to do the above query correctly though.

Please Sign in or register to post replies

Write your reply to: