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;

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

2 thoughts on “Fast access items in an SPListCollection

  1. Kristopher says:

    I stumbled across this looking for more than two ways to check:


    Got any ideas?

  2. Ah, that old chestnut – short answer, nope – I always try, and catch the exception.

    Failing to get the list throws an SPException. Actually, I’ll think I’ll blog about getting different levels of the hierarchy and the exceptions they throw today (14-Oct-2010)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.