There’s been a little chatter recently about the script statement limit and specifically around sorting algorithms in Apex.
Instead of burying the solution deep in the annals of the discussion boards, Jon has convinced me to start publishing again. For those that haven’t been reading this blog since the days it was proudly branded "sforce", my last post was on 6/13/2005!
Needless to say that’s been too long and speaking of that, you’re probably saying get on with it already so I will 🙂
It all started with this little post back when Apex was in developer preview at which time we had not yet exposed a sort() method on the collection types (Array/List). We quickly corrected this and for collections of primitives a quick call to sort() will re-order the list in ascending order.
Great for primitives but what about other types? SObjects for example…. perhaps everyone’s favorite standard object – Opportunity?
Before you get caught up or miss the obvious reaction to the following example I will admit it’s fairly contrived. If all you want to do is sort opportunities on amount you should do so within your SOQL statement directly (see ORDER BY). Please bear with me for this example as I will tie this technique into my next post regarding a sorting and grouping solution as sought by this thread.
While it may be easy to fall back to a custom sorting algorithm a combination of the standard List.sort() method and associative arrays (Maps) can provide a significantly reduced statement footprint.
Let’s take a look at some code that demonstrates the approaches:
If you take the code above and save it into your Developer Edition account as a new class you can run these tests to see how they compare with your data. In my account the results were pretty significant:
Moral to the story: associative arrays and methods on the standard types are great assets to minimize the # of script statements needed to achieve the desired outcome.
It’s good to be back!