mandag den 28. oktober 2013

Using Axes.GetDescendant vs. Axes.SelectSingleItem

I've come across an interresting problem, where people are using the SelectSingleItem function, when they could be using GetDescendant.

Here is some sample code to test the difference between those two performance wise:

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            
            for (int i = 0; i < 10; i++)
            {
                rootItem.Axes.GetDescendant("Test Article 2/Test Subarticle 1/Test Subsubarticle 1");
                rootItem.Axes.GetDescendant("Test Article 2/Test Subarticle 1/Test Subsubarticle 2");
                rootItem.Axes.GetDescendant("Test Article 2/Test Subarticle 1/Test Subsubarticle 3");
            }

            stopWatch.Stop();
            TimeSpan ts1 = stopWatch.Elapsed;

            stopWatch = new Stopwatch();
            stopWatch.Start();

            for (int i = 0; i < 10; i++)
            {
                rootItem.Axes.SelectSingleItem("Test Article 2/Test Subarticle 1/Test Subsubarticle 1");
                rootItem.Axes.SelectSingleItem("Test Article 2/Test Subarticle 1/Test Subsubarticle 2");
                rootItem.Axes.SelectSingleItem("Test Article 2/Test Subarticle 1/Test Subsubarticle 3");
            }

            stopWatch.Stop();
            TimeSpan ts2 = stopWatch.Elapsed;

            litResult.Text = string.Format("GetDescendant: {0} ms, SelectSingleItem: {1} ms.", ts1.TotalMilliseconds, ts2.TotalMilliseconds);

This results in:
GetDescendant: 9,2628 ms, SelectSingleItem: 22,5741 ms.
The numbers vary a bit from each run, but it averages out at SelectSingleItem being about 2.5x times slower than GetDescendant - now imagine using SelectSingleItem in a sublayout loaded on every page view, that cannot be cached...

So, why is there even a SelectSingleItem function on the Axes class, one might ask?

SelectSingleItem uses XPath to lookup the item, which also explains why it is slower than GetDescendant (which just crawles down the tree).

So, what to take away from this?

If you just need to look up an item below the current item, use GetDescendant - and if you need to use XPath, use SelectSingleItem.

Ingen kommentarer:

Send en kommentar