Fast access items in an SPListCollection

What’s the fastest way to access an SPList in an SPListCollection? Well, I can see two alternative ways of getting the list, so I thought I’d test them…

First off, we could get the item by just trying to get it and catching the exception if we fail:

SPList listVariable;
try {
listVariable = mySite.Lists["ListIWant"];
} catch (Exception e) {}

Or we could loop through the lists:

SPList listVariable;
foreach( SPList tempList in mySite.Lists){
if(tempList.Title == "ListIWant") {
listVariable = tempList;
break;
}
}

So, to test this, I built a little test application on the console.

What I found was that loop was always faster. I didn’t try with really large numbers of lists (I only tried up to 20), but I did find that for any probability of the list existing, looping through all the lists was much, much faster (at least 4 times, when the probability of the list we’re looking for was 1; i.e. the list definitely existed!)

There did seem to be a slight load time the first time we accessed the SPWeb.Lists collection, but you have to do that for either method.

Fast access items in an SPListCollection