0

Performance-wise which of these methods is the best way to get a list item collection, and why?

SPList list = web.getlist("listurl");
SPListItemCollection items = list.getItems(query);
foreach(SPListItem item in items)
{
 ......
}

or

foreach(SPListItem item in web.getlist("listurl").getItems(query))
{
   ....
}
7
  • 1
    There is no real difference in what you are doing. The first one has a better readability though. Aug 7, 2013 at 10:29
  • wouldnot it will query list and try to get items again and again in second one? Aug 7, 2013 at 10:30
  • Maybee if it was javascript or something. But not in C#. But I would write is as in the first example anyway, for the readability Aug 7, 2013 at 10:32
  • I can see difference, first one is 00:00:01.2412859 whereas second one is 00:00:01.234146 on a demo list Aug 7, 2013 at 10:49
  • 1
    I bet it will not, since the extra milliseconds most probably is due to the variable binding, or some external factor. For more items, you will not do more variable bindings. And anyway, if it would do the list query every iteration, the gap would be much wider than a couple of milliseconds Aug 7, 2013 at 10:59

1 Answer 1

1
foreach(SPListItem item in web.getlist("listurl").getItems(query))
{
   ....
}

This is wrong approach:

The reason is SPListItemCollection is created for each cycle of the foreach. Ex: 100 ListItem fetched from query each time SPListItemCollection object created from web. It will create you best performance issue. To avoid that you should define the object before use it in the foreach.

1
  • This is not javascript, the collection will not be returned everytime, it will be cached. Oct 28, 2013 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.