April 17, 2012

Performance analysis: Use SPList.ItemCount instead of SPList.Items.Count

Here is the code that can measure performance between two:

   1:  Stopwatch sw = new Stopwatch();
   2:   
   3:              using (SPSite site = new SPSite("http://site/"))
   4:              {
   5:                  using (SPWeb web = site.OpenWeb())
   6:                  {
   7:                      SPList list = web.GetList("/Lists/list");
   8:                      long totalMemory = 0;
   9:                      long totalCollectionCount = 0;
  10:                      Console.WriteLine("Good test");
  11:                      totalMemory = GC.GetTotalMemory(false);
  12:                      totalCollectionCount = GC.CollectionCount(0);
  13:                      sw.Start();
  14:                      Console.WriteLine("item count:{0} ", list.ItemCount);
  15:                      sw.Stop();
  16:                      Console.WriteLine("Total time taken:{0}", sw.Elapsed);
  17:                      Console.WriteLine("TotalMemory:{0}", GC.GetTotalMemory(false) - totalMemory);
  18:                      Console.WriteLine("CollectionCount:{0}", GC.CollectionCount(0) - totalCollectionCount);
  19:   
  20:                      GC.Collect();
  21:   
  22:                      Console.WriteLine("\nBadTest");
  23:                      totalMemory = GC.GetTotalMemory(false);
  24:                      totalCollectionCount = GC.CollectionCount(0);
  25:                      sw.Start();
  26:                      Console.WriteLine("item count:{0} ", list.Items.Count);
  27:                      sw.Stop();
  28:                      Console.WriteLine("Total time taken:{0}", sw.Elapsed);
  29:                      Console.WriteLine("TotalMemory:{0}", GC.GetTotalMemory(false) - totalMemory);
  30:                      Console.WriteLine("CollectionCount:{0}", GC.CollectionCount(0) - totalCollectionCount);
  31:   
  32:                      Console.WriteLine("Press Any key to exit...");
  33:                      Console.ReadKey();
  34:                  }
  35:              }
Results of your testing will depend upon items in list for Items.Count but it will be constant for Items.ItemCount

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment