Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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))
{
   ....
}
share|improve this question
1  
There is no real difference in what you are doing. The first one has a better readability though. –  Robert Lindgren Aug 7 '13 at 10:29
    
wouldnot it will query list and try to get items again and again in second one? –  Customized Name Aug 7 '13 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 –  Robert Lindgren Aug 7 '13 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 –  Customized Name Aug 7 '13 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 –  Robert Lindgren Aug 7 '13 at 10:59
show 2 more comments

1 Answer

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.

share|improve this answer
    
This is not javascript, the collection will not be returned everytime, it will be cached. –  Robert Lindgren Oct 28 '13 at 16:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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