The art of efficient code

In my last post, I’ve written a simple method to retrieve the youngest child. Lars, colleague Sitecore evangelist, pointed me on my usage of iterators and indexes. So’ve decide to do some optimising on the code. The results when running the code 100 times where unbelievable:

Timing of section ‘Unoptimized’: 436,523636383954
Timing of section ‘Optimized1’: 24,8905936369008
Timing of section ‘Optimized2’: 34,3272678510816

Optimasation1 generally uses only iterators to loop trough the children:

IEnumerator children = parent.Children.GetEnumerator();
children.MoveNext();
Item youngestChild = children.Current as Item;

while (children.MoveNext())
{
if ((children.Current as Item).Publishing.PublishDate < youngestChild.Publishing.PublishDate)
{
youngestChild = children.Current as Item;
}
}

return youngestChild;

I generally dislike the casting of the objects. Guess this could be resolved by taking advantage of the Generics model in the CLR2.0, but for now, collection converting is to expensive.  Introducing a help variable in the while-loop isn’t an option as poping another reference on the stack which will only re-used in 1 of n times will only slow down…

The second optimalisation is written based on the first experiences, but now as main goal constructing readable/manageble code:

Sitecore.Collections.ChildList children = parent.Children;
Item youngestChild = children[0];
foreach(Item child in children)
{
if (child.Publishing.PublishDate < youngestChild.Publishing.PublishDate)
{
youngestChild = child;
}
}

return youngestChild;

The meaningless iterator is replaced by a the ChildList which implements IEnumerable and the while is replaced with a nice foreach loop. Altough you would expect the code to be less optimized(as I walk twice trough the first item, etc), this code is actually faster :P. Results after a rerun (100.000 cycles this time):

Timing of section ‘Unoptimized’: 499207,361270776
Timing of section ‘Optimized1’: 33562,6385476366
Timing of section ‘Optimized2’: 32503,9732703458

The message Sitecore produces because of the page did load a long time was also quite funny ;): 11980 11:10:48 WARN Timing threshold exceeded for web page. Milliseconds: 592527,96. Threshold: 1000. Page URL: /Dummy.aspx

The coolest stuff about this bench is definitelly that I haven’t done any codepath optimalisation. Haven’t looked at a way to improve the algorithm, etc. Guess I can win some additional time altough I can imagine the time spent on those last optimalisations aren’t interesting when you win just below the 2% of this code piece…

Still interested anyway in ways to improve this piece of code / functionality 😛

One thought on “The art of efficient code”

  1. Good example. Also because it clearly illustrates that you can, with benefits, use some of the traditional Sitecore methods to retrieve items, and they often prove very fast.

    — Lars

Comments are closed.