Tuesday 22 September 2015

Tips to improve performance while coding using Object Model.

Accessing List Items:
             It is always good if we get the  Items collection and then loop through each item in collection, rather than using Item Collection object in for loops.

Bad Coding: 
              SPList list  = SPContext.Current.List;
              for(int i=0;i<list.items.Count;i++)
              {
                   SPListItem listItem  =  list.items[i];
              }

Good Coding:

              SPListItemCollection items  = SPContext.Current.List.items;
              for(int i=0;i<items.Count;i++)
              {
                   SPListItem listItem = items[i];
              }
Note:Most of us will get complete item collection then we later check a condition.
It is good practice to get only necessary rows and columns rather then complete 
collection,which will improve the performance as well.
 
Using SPQuery to get specific rows:
 SPQuery query = new SPQuery();
 query.RowLimit = 100;//Limiting the number of rows to retrieve.
 SPListItemCollection items = SPContext.Current.List.GetItems(query);
 
Using SPQuery to get specific Columns:
SPQuery query =  new SPQuery();
query.ViewFields = "<FieldRef Name='ID'/><FieldRef Name='Name'/>"
SPListItemCollection items = SPContext.Current.List.GetItems(query);
Always check with SPDisposeCheck tool to avoid unnecessary memory leeks.
SPDisposeCheck: 
It is good practice to run all your projects through SPDisposeCheck tool 
before doing any deployments.

No comments:

Post a Comment