Just recently I’ve had the joy of creating a web part that reads a list.  It was decided the list data needed to be presented in a better way with the ability to page the data and drill down.

I created the part and it looked pretty good, I thought, then came the time to test it.  It worked fine for me but that was before I populated it with 100 items with 5 items it was fine, of course.  Bugger.

Well I spent a fair few hours ripping my code apart, its strange when you optimise code as you look at it with different eyes and what seemed good sensible ideas, became glaring monstrosities.  In a few dev cycles I brought the times down from 16 seconds to render the part to 10, to 4.

But four seconds!!!  Thats rubbish.

I had object cached almost everything in sight, I’d removed loads of control creates and just raw HTML’d the lot I got to the point I was checking every string concatenation was done efficiently.  I even tried to get DevPartner community edition to see where the bottlenecks where (this just did not work, great for windows apps, but could not get this working for sharepoint (if you have leave a clue)).

Luckily for me others in our team had come across slow list API before, and spent days figuring it out so I looked in their code and spotted one line of code they did that I didn’t, but that couldn’t be it surely.

I had been doing the equivalent to this.

SPList selectedList;
selectedList= currentSite.Lists[“Locations”];

string Title=selectedList.Items[“Title”].ToString();

Obivously I had more than just title to display and used the same technique all the way down. However by doing this

SPList selectedList;
SPListItemCollection myItems;
selectedList= currentSite.Lists[“Locations”];
myItems=selectedList.Items;

string Title=myItems[“Title”].ToString();

This gave HUGE performance increases. Apparently and I’ve yet to find the article myself, but the lads told me they read that unless you object cache the items collection it hits the DB but assigned to a local variable and it caches the data.  This would appear to be the case based on the speed increase I have seen here.

So next time your list access is slow  try the above.

tags: , , , ,

Advertisements