Posts Tagged ‘Performance’

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In one of my previous posts I talked about "Using the SPField.JSLink property to change the way your field is rendered in SharePoint 2013". That article talks about how we can set the JSLink property in our SharePoint solutions and how we easily can change the rendering of a field in any list view.

It’s pretty slick and I’ve already had one client make use of the functionality in their pilot SharePoint 2013 farm. However I got a comment from John Lui asking about what the performance would be like when executing the same iterative code over thousands of items. Since I hadn’t done any real tests with this myself, I thought it’d be a good time to try and pinpoint and measure if the client-side load times differ while using the JSLink property.

Measurements

The tests will be performed WITH the JSLink property set and then all tests will be executed WITHOUT the JSLink property set.

I’ve set up my scenario with various views on the same list. The total item count of the list is 5000 items, but we’ll base our tests on the limit of our views:

Test 1  
View Limit 100
Test 2  
View Limit 500

The results will be output with a difference between using the JSLink property and not using it. Should be fun.

Tools

I’be been using these tools for measuring the performance on the client:

Fiddler4, YSlow, IE Developer Tools

The code that will be executed will be the same JavaScript code as I had in my previous article.

SharePoint 2013 browser compatibility

If you intend to measure performance on various browsers, make sure you’ve pinned down what browsers are actually supported by SharePoint 2013. The following versions of browsers are supported:

  • IE 10, IE 9, IE 8
  • Chrome
  • Safari
  • Firefox

Let’s start measuring

Let’s start by taking a look at how I’ve done my tests and what the results were.

Testing methods

Each test was executed 100 times and the loading time result I’ve used for each test is the average of the 100 attempts. These tests are executed in a virtual environments so obviously the exact timings will differ from your environments – what’s mostly interesting right here though is the relative difference between having JSLink set and not set when rendering a list view, so that’s what we’ll focus on.

I’ve performed these tests on IE 10 and the latest version of Firefox. Since older browsers may handle scripts in a less efficient way than these two versions of the browsers, you may experience different results when using for example IE 8.

Results overview

SharePoint 2013 is pretty darn fantastic in its way that it renders the contents and pages. The measurements I’ve done here are based on the entire page and all contents to load. The chrome of the page (Navigation/Headers etc) loads instantly, literally in less than 25ms but the entire page takes longer since the content rendered for the list view will take considerably longer. Here’s the output…

Using 100 Item Limit in the View

image

Difference: 969 milliseconds

Conclusion

There’s not really much to argue about with the default 100-item limit. There’s a difference on almost one second, which is pretty bad to be honest. I would definitely revise these scripts and optimize the performance if I wanted quicker load times. However, if I changed the scripts and removed the rendering of images and used plain text instead, there was very little difference. So I guess it comes down to what you actually put into those scripts and how you optimize your JavaScript.

Using 500 Item Limit in the View

image

Difference: 529 milliseconds

Conclusion

The load times are naturally longer when returning 500 items, but the difference was smaller on a larger result set. I also performed the same tests using 1000 item limit in the view, and the difference per page load was between 500ms to 1000ms, essentially the same as these two tests. If your page takes 7-8 seconds to load without the usage of JS Link like these samples did in the virtual environments, I’d probably focus on fixing that before being too concerned about the impact the JS Link rendering process will have on your page. However, be advised that if you put more advanced logic into the scripts it may very well be worth your while to draft up some tests for it.

Things to take into consideration

  • The sample script here only replaces some strings based on the context object and replaces with an image. No heavy operations.
  • Replacing strings with images took a considerably longer time to render than just replacing text and render. Consider the code you put in your script and make sure you’ve optimized it for performance and scope your variables properly and so on.
  • Take your time to learn proper JavaScript practices. It’ll be worth it in the end if you’re going to do a lot of client side rendering stuff down the road.
  • If you’ve got access to Scot Hillier’s session from SPC12, review them!

Summary

Its not very often I’ve seen anyone use 1000 items as the item limit per view in an ordinary List View Web Part. Most of my existing configurations are using 100 or less (most likely around 30) items per page for optimal performance – however should you have larger views you should of course consider the impact the rendering will have if you decide to hook up your own custom client side rendering awesomeness.

You’ll notice the biggest difference between page load times if you’ve got a smaller item row limit in your view, simply because it looks like using the custom JS link property adds between 500 – 1000 milliseconds whether if I’m returning 100 items, 500 items or 2500 items in my view. Worth considering.

With that said – It’s a pretty cool feature and I’ve already seen a lot of more use cases for some of my clients to utilize these types of customizations. It’s a SUPER-AWESOME way to customize the way your list renders data instead of converting your List View Web Part (or Xslt List View Web Parts and so on) into Data View Web Parts like some people did with SharePoint Destroyer.. Err.. SharePoint Designer. For me as a developer/it/farm admin guy this will make upgrades easier as well (hopefully) as the list itself will be less customized, and only load an external script in order to make the customizations appear. Obviously I’m hoping for all scripts to end up in your code repositories with revision history, fully documented and so on – but then again I do like to dream :-)

Enjoy.

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 8 (this article):
As most of you know, in any ASP.NET project (SharePoint included) there’s something you know as ViewState.  With the ViewState we can persist state of our properties in the page controls and objects across postbacks that happen in our solutions. If we are not careful and plan the usage of ViewState properly, we can end up with a performance hit that will slightly decrease the performance in the page rendering process.

In this article we will take a look at what impact the ViewState can have if we “forget about it”, and of course how we can prevent our pages from being unnecessarily big in page size.

ViewState in our SharePoint projects

If you’ve been developing SharePoint projects of any type, you’ve most certainly been doing some kind of asp.net UI development as well. (Application Pages, Web Parts, User Controls and so on) that are inheriting the asp.net capabilities and hence the ViewState.

What you should know as an ASP.NET developer: Be sure to know when you should, or shouldn’t use the ViewState. You can disable the usage of ViewState for certain components, or the entire page.

Performance considerations

With an increased ViewState you get an increased Page Size which in turn obviously means that the page will take a bit longer to render.

We’ll take a quick look at how the performance can differ when we’re using ViewState and when we’re disabling the ViewState in a SharePoint project.

Taking a look: ViewState

In order for us to really understand what impact the ViewState can have on the page rendering process, we’ll dig into the details of the what the ViewState looks like. To do this we can check out the source of the rendered page, and of course we’ll rely on our faithful squire; Fiddler2.

Before we’ll start digging with the Fiddler2-application, we can simply check the Page Source of any given page being rendered and we’ll most likely find a heap of ViewState madness going on in there.

In my sample application that only consist of a simple GridView control and a few rows of data – the ViewState is turned into this:

 <input type= "hidden "

 

  name= "__VIEWSTATE "

 

  id= "__VIEWSTATE "

 

  value= "/wEPDwULLTE5NjIxMzI1MDIPZBYCZg9kFgICAQ9kFgQCAQ9kFgICDw9kFgJmD2QWAgIBD

 

  w8WAh4HVmlzaWJsZWdkZAIDD2QWBgIRD2QWBGYPZBYEAgEPZBYCZg9kFgQCAg9kFgYCAQ8WAh8Aa

 

  GQCAw8WCB4TQ2xpZW50T25DbGlja1Njcm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HwBoZGQYAgUfY3RsM

 

  DAkUGxhY2VIb2xkZXJNYWluJEdyaWRWaWV3MQ88KwAKAQgCKWQFR2N0bDAwJFBsYWNlSG9sZGVyV

 

  G9wTmF2QmFyJFBsYWNlSG9sZGVySG9yaXpvbnRhbE5hdiRUb3BOYXZpZ2F0aW9uTWVudVY0Dw9kB

 

  QRIb21lZGnihW5zRhNmmnQef2E5KXJlKgIU" />

 

If you compare the aforementioned ViewState with the very same page but with the ViewState disabled, it would look like this:

 <input type="hidden"

 

  name="__VIEWSTATE"

 

  id="__VIEWSTATE"

 

  value="/wEPDwULLTE5NjIxMzI1MDJkGAIFH2N0bDAwJFBsYWNlSG9sZGVy

 

  TWFpbiRHcmlkVmlldzEPPCsACgEIAilkBUdjdGwwMCRQbGFjZUhvbGRlclR

 

  vcE5hdkJhciRQbGFjZUhvbGRlckhvcml6b250YWxOYXYkVG9wTmF2aWdhdG

 

  lvbk1lbnVWNA8PZAUESG9tZWTEsK7AlAZmIZYt/bke1dmkbPKxhg=="/>

 

What impact can these few lines of markup have on the page rendering process anyway, you say? Well, in order to find out – let’s summon our good friend Fiddler2 and do a quick comparison.

ViewState Enabled

ViewState Disabled

Body size (bytes) 14 534 bytes 12 883 bytes
Load time (seconds) 0.3765430 seconds 0.2031263 seconds

A visual comparison of the same page with versus without ViewState enabled:

Body Size comparison (bytes)

Load Time comparison (seconds)

image image

So what can I do to tune and tweak the ViewState?

There’s generally two good initial tips for tuning the ViewState.

  • Disable ViewState for the entire page
  • Disable ViewState for selected components

The first option is good if you don’t need to use ViewState in any of the components on your page. Then you can simply disable ViewState by setting the ViewStateEnabled property to false:

  <%@ Page Language="C#"

 

     AutoEventWireup="true"

 

     CodeBehind="ViewStateSample.aspx.cs"

 

     Inherits="Zimmergren.Samples.ViewState.ViewStateSample"

 

     DynamicMasterPageFile="~masterurl/default.master"

 

     EnableViewState="false"  %>

 

The second option is good if you need the ViewState for certain components, but you want to disable it for others. You can disable the ViewState for specific components;

     <asp:GridView ID="GridView1"

 

         runat="server"

 

         AutoGenerateColumns="False"

 

         AllowSorting="true"

 

         AllowPaging="true"

 

         PageSize="25"

 

 EnableViewState="false"

 

         />

 

Additional Tip: Take a look at HTTP compression

In addition to being aware of the ViewState in any asp.net project, you should take a look at HTTP Compression that you can enable in IIS.

Read more on HTTP Compression

Summary

Alright – the summer is officially over (at least of you take a look at the recent weather) and I’m back in the saddle. In this article I’ve been talking a bit about how the ViewState can impact your performance in any asp.net project (hence SharePoint project). The reason for talking about it is that I’ve seen quite the amount of projects as of late that doesn’t think about the impact a huge ViewState can have on the time it takes to download and render a page on the client.

An important consideration that I’ve learned throughout all our projects to create Internet-facing sites based on SharePoint (or plain old ASP.NET) is to measure the performance in different scenarios, including some stress testing and load tests. In most of these projects we’ve seen an increased performance if we take time to select what components or pages should disable ViewState. It might be worth considering.

Note that this is a minimal sample with minimal impact. Consider when you’ve got a huge page with 10+ Web Parts and all using the ViewState, even if they don’t really need to – can you imagine the page load times increasing? The answer is probably yes :-)

Enjoy.

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 7 (this article):
This article is a bit shorter than the others and will only cover the concept of crunching your script files in your projects. The reasoning behind a crunched file is to save on transfer-bytes between the client and server.

JavaScript crunching

The technique called script crunching (or JavaScript crunching) is often referred to a way of eliminating useless characters from the script files to allow them to load faster. This means that by eliminating unnecessary whitespaces, line breaks and putting semicolons in the right places you can achieve a file size that is smaller than the original.

The reasoning behind crunching the script files are much that you can save on the client/server transfer and therefore also minimize the HTTP requests – which in turn is one step in the right direction for minimizing the page load time and render time.

Short in short; Do consider the technique if you’ve got large scripts that are taking a bit too long to load.

SharePoint 2010 are using crunched scripts

In SharePoint 2010 we already have a few examples of where JavaScript crunching is working in action. One example is the SP.js file which is essentially a crunched JavaScript library in SharePoint 2010. You do however also have the ability to use the SP.debug.js which contains the same content, but without being crunched.

When you look at those two files in an editor, you’ll quickly see the difference between them:

SP.js – 381 KB – Crunched JavaScript file in SharePoint 2010
image

SP.debug.js – 561 KB – The same file, but without the crunch
image

You can see that the mail difference between these two files is the file size. This means that if you’ve using the crunched version of the JavaScript file, your application will load slightly faster.

How to: Crunch your script files

There’s tons of tools on the market for crunching your scripts. Here’s a few online tools for crunching those scripts:

(or just search for JavaScript crunch, and you’ll find all the tools you’ll ever need)

What is the difference when using crunched scripts?

As a quick summary I did a test with an application that are loading a somewhat large script file – first without any crunching and then the same application loading the files after they’ve been minimized with a crunch. These are the results in my SharePoint 2010 application.

Without crunching

After crunching

JavaScript file size: 445871 bytes
(435 KB)
JavaScript file size: 331798 bytes
(324 KB)
  Saves around 25.5% in file size

image

Summary

A brief summary of the result is that if you’re crunching your script files, you’ll get a slightly smaller footprint when loading the page and making the HTTP requests. The reason for bringing this to your attention is of course that it’s a technique that’s been around for quite some time, but people tend to miss out on it because they’ve not seen the results of it. So, here you go – a visual chart telling you how it differs to use the exact same script, with and without crunching.

Enjoy.

SP 2010: Developing for performance Part 6 – CSS Sprites

April 8th, 2011 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 6 (this article):
In web development today its very important to keep performance in mind – this is especially important in any site that is published externally or for whatever reason will have heavy traffic. In this article I will briefly cover the area of CSS Sprites, how they are implemented in SharePoint 2010 and of course how you can create them yourself.

Introduction to CSS Sprites

What are CSS sprites anyway?

CSS sprites is a technique used to reduce the number of requests for images on a site when visiting it. Normally when you see a web site today there’s plenty of files being requested and loaded upon the request made. With the use of CSS sprites we can reduce the amount of files that we need to request from the server by consolidating many image files into one file and use CSS to display the correct part of that consolidated image when it needs to depict your specific image.

Short in short: Take a bunch of separate images and smack them together to one single file. Voila, you’ll only need to request one file from the server.

SharePoint 2010 and CSS Sprites

So why are we talking about CSS sprites here anyway, isn’t this supposed to be all about SharePoint and awesomeness? But of course, and that’s exactly why we’re talking about it – CSS sprites are a natural part of a normal SharePoint 2010 installation. By default, there’s CSS sprite techniques used to render and display images in (for example) the Ribbon menu.

These are some samples of images used with CSS sprites in SharePoint 2010:

FGIMG.PNG jsgridcluster.png
FGIMG jsgridcluster

As you can see in any of the two images above the many small images/icons have been smashed together into one single image file and then there’s some CSS magic to position it. This is basically what it’s all about.

Why should I bother learning to use CSS sprites?

This would be like asking yourself the question "Why would I develop something that is of great performance" or "Why would I do something awesome". No more rhetorical questions please ;-)

Of course the reasoning behind creating CSS sprites are that you can develop web applications that can reduce the page load and enhance the performance of your sites and make them load quicker and be more responsive.

Creating CSS sprites for my applications? How?

There’s a few ways to create CSS sprites for you own applications.

  • Do it manually.
    • This approach requires a lot from you (the designer) in order to hack it up properly and make sure it’s pixel-correct.
  • Do it using a tool
    • This approach is what I normally use.
    • With any of the tools on the market to create CSS sprites you’re better off than doing it manually – all you have to do is dump you images into an application and it’ll output one single image along with the CSS markup for that. Awesome.

For obvious reasons mentioned above I will not be demonstrating how to do this manually but will rather be using any of the hundreds of tools out there to create the sprites.

In this example I’m going to use my main man Waldek’s tool called SpriteGenerator.

There’s a bunch of other tools available to create and generate these sprites as well of course, bing.com is thy friend.

How to: Generate CSS sprites using a tool

In this section I’ll talk you through our current application and what it looks like, what we want to achieve and finally how to achieve it.

Our current application, a visual sample

This is my current sample application before we start using sprites.

Control Panel Web Part (dummy):
image

This is the Visual Studio project, containing all the images and resources:
image

As you can see there’s quite some images being loaded. The images used in the application (my Web Part) will be fetched using a normal HTTP-request and that’s when one could realize how quickly those small requests can add up to impact performance.

This application uses some generic HTML markup like this:

         <div  class="width300p"> 
             <div  class="leftalign floatleft width30"> 
                 <div  class="height70p"><asp:Image  ID="Image2"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/mail.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image3"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/message.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image4"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/more.png"  /></div> 
             </div> 
             <div  class="centeralign floatleft width30"> 
                 <div  class="height70p"><asp:Image  ID="Image5"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/notebook.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image9"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/search.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image13"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/favorites.png"  /></div> 
             </div> 
             <div  class="width30 floatright"> 
                 <div  class="height70p"><asp:Image  ID="Image6"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/info.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image7"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/logoff.png"  /></div> 
                 <div  class="height70p"><asp:Image  ID="Image8"  runat="server"  ImageUrl="/_layouts/images/TOZIT.CSSSprites/question.png"  /></div> 
             </div> 
         </div>

Now, in order for us to utilize the CSS sprites instead, and not have to make a request for each of the images separately – we’ll use the SpriteGenerator and create us some nice CSS sprite magic.

Using the Sprite Generator to make some magic

Like I said before, we’ll be using Waldek’s SpriteGenerator for this sample.

Just open it, put in the images you’d like for it to make some magic with and then simply hit the magic button.

Tip: Check out how to use the SpriteGenerator here

The result of using the SpriteGenerator can look something like this:
image

This is one consolidated image containing all the graphic from my application. But instead of having about 30 different icons in my project, I now have only one.

The generator will create the CSS needed as well, and it can look something like this:

.sprite { background: url(‘/_layouts/images/TOZIT.CSSSprites/TOZIT_Sprite.png’) no-repeat top left; }
.pc { background-position: -0px 0; width: 47px; height: 64px; }
.question { background-position: -47px 0; width: 53px; height: 64px; }
.info { background-position: -100px 0; width: 54px; height: 64px; }
.mail { background-position: -154px 0; width: 54px; height: 64px; }
.more { background-position: -208px 0; width: 54px; height: 64px; }
.user { background-position: -262px 0; width: 55px; height: 64px; }
.world { background-position: -317px 0; width: 55px; height: 64px;  }
.video { background-position: -372px 0; width: 56px; height: 64px; }
.favorites { background-position: -428px 0; width: 57px; height: 64px; }
.edit { background-position: -485px 0; width: 60px; height: 64px; }
.date { background-position: -545px 0; width: 64px; height: 57px; }
.file { background-position: -609px 0; width: 64px; height: 64px; }
.group { background-position: -673px 0; width: 64px; height: 58px; }
.home { background-position: -737px 0; width: 64px; height: 62px; }
.left_arrow { background-position: -801px 0; width: 64px; height: 59px; }
.logoff { background-position: -865px 0; width: 64px; height: 78px; }
.notebook { background-position: -929px 0; width: 64px; height: 51px; }
.rigth_arrow { background-position: -993px 0; width: 64px; height: 57px; }
.search { background-position: -1057px 0; width: 64px; height: 61px; }
.sound { background-position: -1121px 0; width: 64px; height: 58px; }
.stop { background-position: -1185px 0; width: 64px; height: 59px; }
.vault { background-position: -1249px 0; width: 64px; height: 53px; }
.message { background-position: -1313px 0; width: 66px; height: 64px; }
.image { background-position: -1379px 0; width: 84px; height: 84px; }
.tozitlogo { background-position: -1463px 0; width: 250px; height: 101px; }

Now, what this really means is that you now have the ability to actually use only one single image to portray several.

New Visual Studio structure

Obviously, with the new update and only using one single image – the Visual Studio project might look something like this:

image

New HTML markup

And finally, there needs to be some changes in the HTML markup to reflect the changes with the images. The markup could look something like this:

         <div  class="leftalign floatleft width30"> 
             <div  class="height70p sprite mail">&nbsp;</div> 
             <div  class="height70p sprite message"  >&nbsp;</div> 
             <div  class="height70p sprite more"  >&nbsp;</div> 
         </div>

How does using CSS Sprites affect requests, hence performance?

Dealing with sprites isn’t very hard to get started with as you saw in the previous short samples. But what’s more interesting from a performance perspective is of course how it can affect the performance of the requests being made towards the server.

Let’s do some generic Fiddler-magic to see what the requests look like without using sprites and then what the requests look like with the use of sprites.

Fiddler test 1: NOT using CSS sprites

image

Request Count 17 total requests made to the server!
Bytes Sent 8 137 bytes
Bytes Received 76 164 bytes

Fiddler test 2: Using CSS sprites

image

Request Count 3 total requests made to the server!
Bytes Sent 1 722 bytes
Bytes Received 139 369 bytes

What you can easily conclude from the initial tests is that there’s more requests without the CSS sprites, while the size can be slightly larger for a consolidated image when using the sprites.
It’ll load and render quicker by downloading only the 3 files instead of the 17 files due to the aggregation time it takes to render the content.

Visualize the results, please!

Using CSS sprites
(Time in seconds to load the data)
NOT using CSS sprites
(Time in seconds to load the data)
image image

RESPONSE BYTES
image/png:    120 250
text/html:    16 593
~headers~:    1 748
text/css:    778

RESPONSE BYTES
image/png:    52 417
text/html:    16 709
~headers~:    6 260
text/css:    778

ACTUAL PERFORMANCE
Aggregate Session time:   
00:00:00.531 (0.5 seconds)
Sequence (clock) time:
00:00:00.4281250 (0.4 seconds)

ACTUAL PERFORMANCE
Aggregate Session time:
00:00:01.390 (1.3 seconds)
Sequence (clock) time:
00:00:00.5625000 (0.5 seconds)

I did some tests with two machines, two different projects and a couple of clients to request the pages and the results (on average) was something like this in rendering time. The chart below is a relative visualization of the results per average.

Chart

Summary

The impact of a system with a lot more requests for data than these samples, more users and in generally more traffic would differ a bit more than the charts here. Using sprites in combination with caching the data is a good practice to keep the amount of requests to the server to a minimum.

Even if this minor change don’t have any critical impact on improving the performance it’s important to consider. "All improvements are good improvements".

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 5 (this article):
In SharePoint 2010 (and 2007 for that matter) there’s a few objects in the API’s that requires your special attention in order to behave properly. If you do not consider the disposal patterns and rules set forth, your application may very well suffer performance issues. In this article I will briefly touch upon the subject of disposing your SharePoint objects and foremost enlighten how important it is to dispose the objects!

What does Disposing mean and why is it important?

When I deliver training, there’s always the question about why disposing is important. In SharePoint there’s valid grounds for saying it’s important to dispose, more than just saying "It’s best practice". If you don’t properly dispose some of your objects in SharePoint you’ll quickly face performance issues since those objects don’t get caught and disposed by the Garbage Collector in a timely fashion as most other objects do in .NET.

What is a "dispose pattern"?

http://en.wikipedia.org/wiki/Dispose

The Dispose Pattern is the approach used to properly dispose and clean up the resources you’re using in your projects when programming in .NET (or other runtimes). Normally there’s an automatic garbage collector doing the cleanup for you – but in certain scenarios (like the ones described later in this article), you’ll need to manually dispose your objects.

IDisposable

In Microsoft .NET when an object inherits from the IDisposable interface it means that the Garbage Collector will call the .Dispose() method of that object when it’s no longer used. The Dispose() method in turn calls the Close() method which generally means you should call the .Dispose() method instead of the .Close() method to make sure the objects are properly disposed. Keep reading to see why this is so important!

Why is manual disposal really, really important in SharePoint?

Some of the objects you’re working with heavily in the SharePoint object model (for example the SPWeb and SPSite) are mostly using unmanaged code – and since the managed part of the code is quite small it doesn’t leave a large memory footprint and hence the Garbage Collector don’t necessarily dispose of that object – which means that it’ll be occupying server resources for a longer time if you don’t manually dispose of those objects.

What happens if I forget to dispose?

There’s several things that you may notice in your applications if you’ve implemented a solution that are not properly disposing their objects.

  • Memory consumption.
    • The consumption of your server memory may peak and the worker process (w3wp.exe) may consume a lot more memory than it would normally have to consume.
  • Application Pool recycling.
    • If the worker process consumes too much memory, it’ll recycle the application pool.
    • If you’ve got an underperforming application causing overwhelming  memory consumption the Application Pool will recycle more often.
  • Performance issues!
    • Slow response times
    • Timeouts
    • Unexpected errors
  • Headache
    • User headache
    • Support headache
    • Admin headache
    • Developer headache (ultimately)

In other words: Make sure you’re properly disposing your objects at all times!

Sandboxed Solutions and Resource Usage – Think about dispose patterns!

If you’re developing applications for the Sandbox in SharePoint 2010 (User Code Solutions / Sandboxed Solutions) you may be aware of the resource point system that will limit your application’s usage of resources on the server. This is a great way to keep the admins calm and developers keen on producing quality code.

A thing to note is that if you don’t correctly dispose your objects they will consume more server resources which in turn would lead to the resource points increasing. If the resource usage reaches the limits set forth by SharePoint for a sandboxed solution – it’ll deactivate it.

In other words: Make sure you’re properly disposing your objects at all times!

Let’s visualize the performance problem!

Okay, so now that I’ve got your attention – let’s do a quick performance test to see how the process handles the memory if we create the same application with and without disposal patterns in SharePoint.

I created a simple application that will work heavily with the SPSite and SPWeb objects on one of my servers. After hooking up a performance counter and monitoring the memory consumption repeatedly during a few hours of repeated execution it was easy to line down a conclusion which you can see in the chart below.

Performance summary

The following chart displays the same application with and without implementing the dispose patterns in a SharePoint 2010 execution environment.

Zimmergren Sample Memory Consumption Chart

You can see by the results of the two applications above that when we’re properly disposing our objects there’s a notable difference in the performance in our application – and hence the overall server resource usage.

In other words: Make sure you’re properly disposing your objects at all times!

How to: Implement dispose patterns in your SharePoint code

At this point we know it’s very important to dispose our objects in SharePoint – let’s take a look at how we can do that properly and what tooling and guidelines we can use to help us in this important quest!

Approach 1 – Manually calling Dispose()

The absolutely most general and simple approach to dispose your objects is to simply call the .Dispose() method of your objects:

 SPSite  site = new  SPSite ("http://zimmergren/");
 // Do stuff 
 site.Dispose();

Approach 2 – Encapsulating the statement in a using() block

A more common approach is to encapsulate the code in a using-block where the object will be automatically disposed when we’re reaching the end of our block.

     using (SPSite  site = new  SPSite ("http://zimmergren"));
     {
         // Do stuff 
     } 

Approach 3 – Utilize a try/finally block

Whenever you’re expecting to catch an exception or somehow might stumble onto exceptions and need to handle them – a better approach for disposing is to create a try-finally block and dispose the object in the finally-block.

Sample 1: Without exception handling

     SPSite  site = null ;
     try 
     {
         site = new  SPSite ("http://zimmergren");
         // do stuff 
     }
     finally 
     {
         if (site!=null ) site.Dispose(); 
     }

Sample 2: With exception handling

     SPSite  site = null ;
     try 
     {
         site = new  SPSite ("http://zimmergren");
         // do stuff 
     }
     catch (Exception  ex)
     {
         // Handle the exception 
         // Possibly send it to the logs 
     }
     finally 
     {
         if (site!=null ) site.Dispose();
     }

SharePoint 2010 Logging information: http://zimmergren.net/archive/2011/01/17/sp-2010-developing-for-performance-part-4-logging.aspx

Approach 4 – A mix of the aforementioned approaches

In some scenarios it might be a necessity to mix the aforementioned methods for disposing.

     using (SPSite  site = new  SPSite ("http://zimmergren"))
     {
         foreach (SPSite  oSite in  site.WebApplication.Sites)
         {
             try 
             {
                 // Do stuff 
             }
             catch (Exception  ex)
             {
                 // Log and handle exceptions 
             }
             finally 
             {
                 if (oSite!=null ) oSite.Dispose();
             }
         }
     }

Using SPDisposeCheck.exe to help us check for issues

It’s one thing to be pro-active and think about the dispose patterns when you’re developing your applications – but sometimes you can’t cope for every scenario in your complex code. Don’t worry though – you’ve got one of my best friends to help you out with that – the SPDisposeCheck.exe tool that Microsoft released to check for disposal problems.

Download and install it

There’s a new version of the popular dispose-check tool for SharePoint called SPDisposeCheck. You can find it here: http://code.msdn.microsoft.com/SPDisposeCheck

Grab your copy of the tool and hang on tight for the ride!

Configure it

When you’ve installed the tool, you can see a new menu option in the "Tools" menu:

image

Clicking the "SharePoint Dispose Check" menu item will bring up the SPDisposeCheck configuration menu like this:

image

In this dialog you can configure how the tool should behave, and if it should execute after each build. What’s even cooler is you can choose how to treat the problems.

When you’re building your Visual Studio project, the SPDisposeCheck will perform a post-build command (if you’ve ticked the Execute After Build checkbox) – and you’ll see the output directly in your Error-window:

image

Tip!
Always have this tool installed, and every now and then run the SPDisposeCheck to make sure your code is properly disposing your objects. Otherwise it’ll warn you like in the picture above :-)

False positives

When it comes to checking for dispose problems or leaks with this tool, it can sometimes give you something you’d refer to as "a false positive". What that generally means is that although the tool might report a problem, it really isn’t.

Ignoring reports

Sometimes with the SPDisposeCheck tool you’ll get quite a bunch of "false positives" reported, or for whatever other reason you’d like to ignore certain error messages from the SPDisposeCheck tool – you can do that by implementing the SPDisposeCheckIgnore attribute (available as source code in the SPDisposeCheck installation folder).

The following code snippet is taken from the "SPDisposeCheckIgnoreAttribute.cs" file in the SPDisposeCheck installation folder. Add this code to your project (you can change the namespace..):

 using  System;
 namespace  Zimmergren.SP2010.DisposePatterns
 {
     public  enum  SPDisposeCheckID 
     {
         // SPDisposeCheckIDs. 
         SPDisposeCheckID_000 = 0,  
         SPDisposeCheckID_100 = 100,
         SPDisposeCheckID_110 = 110,
         SPDisposeCheckID_120 = 120,
         SPDisposeCheckID_130 = 130,
         SPDisposeCheckID_140 = 140,
         SPDisposeCheckID_150 = 150,
         SPDisposeCheckID_160 = 160,
         SPDisposeCheckID_170 = 170,
         SPDisposeCheckID_180 = 180,
         SPDisposeCheckID_190 = 190,
         SPDisposeCheckID_200 = 200,
         SPDisposeCheckID_210 = 210,
         SPDisposeCheckID_220 = 220,
         SPDisposeCheckID_230 = 230,
         SPDisposeCheckID_240 = 240,
         SPDisposeCheckID_300 = 300,
         SPDisposeCheckID_310 = 310,
         SPDisposeCheckID_320 = 320,
         SPDisposeCheckID_400 = 400,
         SPDisposeCheckID_500 = 500,
         SPDisposeCheckID_999 = 999 
     }
 
     [AttributeUsage (AttributeTargets .Method | AttributeTargets .Assembly, 
         Inherited = false , AllowMultiple = true )]
     public  class  SPDisposeCheckIgnore  : Attribute 
     {
         public  SPDisposeCheckIgnore(SPDisposeCheckID  Id, string  Reason)
         {
             _id = Id;
             _reason = Reason;
         }
 
         protected  SPDisposeCheckID  _id;
         protected  string  _reason;
 
         public  SPDisposeCheckID  Id
         {
             get  { return  _id; }
             set  { _id = Id; }
         }
 
         public  string  Reason
         {
             get  { return  _reason; }
             set  { _reason = Reason; }
         }
     }
 }
 

Once you’ve done that, you can use the attribute on your methods and assemblies to tell them to ignore that specific item.

Example usage of the SPDisposeCheckIgnore attribute:

         [SPDisposeCheckIgnore (SPDisposeCheckID .SPDisposeCheckID_110, 
             "False Positive, nothing to see here, move along!" )]
         private  static  void  MyAwesomeMethod()
         {
             // Your method code with false positives 
         }
 

What if I’m an awesome coder already?

Too many times have I encountered problems in projects due to not properly checking for memory leaks.

Better safe than sorry. That’s all I’m going to say about that :-)

Summary & Links

What we’ve learned from this article is that you should always keep in mind how you handle your objects in your code – and especially when it comes to the SharePoint objects that are invoking unmanaged code like the SPWeb and SPSite objects (to name two common ones).

Make sure you’ve downloaded the latest version of the SPDisposeCheck tool to get the aforementioned fancy integration into Visual Studio 2010. It’s pretty awesome indeed!

Links / Resources

Enjoy!

SP 2010: Developing for performance Part 4 – Logging

January 17th, 2011 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 4 (this article):
In SharePoint 2010 (well, 2007 too for that matter) you need to think about proper logging in your applications to ensure that any problems, issues or other events are lifted to the ULS Logs (Unified Logging System) – that way the administrators can easily view the logs and track down problems with your applications. In this article I will talk a bit about how you can utilize the logging capabilities in SharePoint 2010.

ULS Logs

The ULS Logs are the main place for SharePoint to output it’s diagnostics information. We will take a quick look at how we can read the logs and obviously how we can write custom logging messages to the logs.

Reading the ULS Logs in SharePoint 2010

In order to read the ULS Logs you’ll need access to the SharePointRoot (14LOGS) folder. But to make the life even easier for us Microsoft released a tool called the ULS Viewer which you can download here: http://code.msdn.microsoft.com/ULSViewer

With this tool you can quite easily read through the logs in SharePoint 2010 without any issues.

There’s plenty of resources on the web about how to use the ULS Viewer, so go take a look at any one of them for some usage-instructions.

Download (docx): ULS Viewer documentation

Writing to the ULS Logs from you SharePoint 2010 application

The other side of the logs are of course writing to the logs. This is not a very hard task to do in SharePoint 2010, and I’ll outline the basic steps to do so here.

Normally I create a new class or at least a method to take care of the logging, and it can look like this:

public static void WriteTrace(Exception ex)
{
    SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
    diagSvc.WriteTrace(0,
        new SPDiagnosticsCategory("TOZIT Exception",
            TraceSeverity.Monitorable,
            EventSeverity.Error),
        TraceSeverity.Monitorable,
        "An exception occurred: {0}",
        new object[] {ex});
}

You can use the aforementioned code by calling the method like so:

try
{
    throw new Exception("Oh no, application malfunctioned! UnAwesomeness!!!");
}
catch(Exception ex)
{
    WriteEvent(ex);
}

It’s not very hard at all – once you’ve done that, you’re all set to kick off your custom applications and just call your custom logging method. Obviously you should create a proper logging class to take care of all your logging in your applications.

Results

Using the ULS Viewer you can easily track down the error messages by filtering on your category (in my case it’s TOZIT Exception)

image

image

Event Logs

Even though the ULS Logs takes care of most of the diagnostics logging today, it might be reasonable to output information into the Event Logs sometime.

Writing to the Event Logs from you SharePoint 2010 application

Just as when you’re doing ULS Logging, you can do logging to the Event Logs. It’s just as simple, but you replace the method "WriteTrace" with "WriteEvent" like this:

public static void WriteEvent(Exception ex)
{
    SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
    diagSvc.WriteEvent(0,
        new SPDiagnosticsCategory("TOZIT Exception",
            TraceSeverity.Monitorable,
            EventSeverity.Warning),
        EventSeverity.Error,
        "Exception occured {0}", new object[] {ex});
}

Results

You can view the logs in the Event Logs on your SharePoint server as you would read any other logs.

image

Can I do more?

There’s plenty of cool things to do with the logging mechanism in SharePoint 2010, so you should definitively get your hands dirty playing around with it.

If you for example want to tag the log entries with your company name, clients name or project name – you can easily change that behavior as well. Take a look at my friend Waldek’s post about it here: http://blog.mastykarz.nl/logging-uls-sharepoint-2010/

Related resources

Summary

As a part of the article series focusing on some general guidelines for performance in your applications, logging is a major player. If you master your logs in terms of monitoring and custom application logging you will quickly come to realize how valuable it is.

This is intended as a starting point for you to get familiar with the logging-capabilities in SharePoint 2010.

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 3 (this article):
In this article I will talk about some different techniques for managing caching in your applications. One of the most important thing for most projects today is to keep the performance to a maximum under heavy load times. Caching helps out in achieving parts of that goal.

Some caching techniques in SharePoint 2010

In SharePoint 2010, there’s a few different ways to cache data. In this section you can read about a few of those approaches. Most of the caching techniques I use regularly as a developer derives from or is a direct usage of the capabilities of the .NET framework.

Output Caching (Configurable)

The concept of Output Caching is something that natively comes with SharePoint 2010, as it builds on and relies on ASP.NET caching techniques. This means that you can configure your SharePoint 2010 site to cache the Pages it outputs. The reasoning behind caching a page is obviously that it takes time to generate the content on any page, and on a heavily accessed site it would be a performance impact to generate a new page on every request – that’s where Output Caching comes in handy.

There’s a few goodies about Output Caching, as well as a few gotchas that you should be aware of before taking the journey of configuring your sites for Output Caching;

  • Positive: Quicker response time for your cached pages, faster to render to the client.
  • Positive: Saves on CPU, since it doesn’t have to re-do all the calculations every time.
  • Positive: You can customize Output Caching by using Cache Profiles.
  • Positive: The caching mechanism can store different versions of the resources cached depending on the permissions for the requesting user.
  • Negative: Caching obviously eats more memory as it needs to cache the pages.
  • Negative: Possibility for inconsistencies between WFE’s in a multi-server farm.
  • Negative: Output Caching is a SharePoint Server 2010 capability.

You can create custom caching profiles for your SharePoint 2010 site which allows you to modify and configure the way things are cached – and what should be cached.

Read more: How to configure Output Caching
Read more: Create a custom cache profile using VaryByCustom event handler

Object Caching (Configurable)

In SharePoint Server 2010 you’ve got the option to use Object Caching as well, which is a mechanism to cache specific page items. This is especially likable if you’re playing around with Cross-List data queries and need to cache the results of such a query.

Read more: Object Caching

BLOB Cache (Configurable)

In SharePoint 2010 you also have something called the BLOB Cache, which is a disk-based caching mechanism that caches resources on the disk. Normally these resources are files served by a web page and are named Binary Large OBjects (BLOB).

Normally the BLOB cache will cache files served by the web request like images and video clips.

In web.config you’ve got something similar to the following line which lets you know what file types are cached. You can of course add or remove file types here:

<BlobCache 
    location="D:BLOB"
path=".(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|wmv)$"
    maxSize="10"
    enabled="false" />

Read more: Configure cache settings for a Web Application (SharePoint Server 2010)
Read more: Configure the BLOB Cache

Caching in code (Programmable)

While we know that there’s pre-configurable caching available in SharePoint 2010 (like the Output Cache and BLOB Cache), there’s obviously still a need to create custom caching routines in your applications.

In order for your custom applications to run efficiently and save on server load, you need to consider the importance of using proper caching in your applications.

For instance, if you’ve created an application that is (on every request) fetching information from a database or a SharePoint list (SPList), do you really need that data to be fetched directly from the source – or could you live with having it cached for a few minutes? If it’s not super-important data we’re dealing with that doesn’t need to be up to date every second and every request – please consider building some caching mechanisms in your applications.

There’s a few different approaches to caching in your custom applications, the most common being the ASP.NET Caching (Read about how you can cache a Web Part).

To be honest, there’s no need to write about all the different code-samples you could use for caching right here, as the guys at Microsoft did an excellent job talking about it in this Best Practice article:

Read more: Common coding issues when working with the SharePoint Object Model

Note that the aforementioned article is for SharePoint 2007 (WSS 3.0) originally, but these techniques still apply.

Summary

In this article you’ve read about a few approaches to make your applications perform better in SharePoint 2010. These techniques are a fundamental part of development and configuration when it comes to playing around with SharePoint and making it behave properly in terms of responsiveness and performance.

I’ve been getting a few requests for talking about some various caching techniques in SharePoint, so there you have it. Go have a read at those links and you should be all set to start the adventure that is caching!

Read more: Planning for caching and performance

Enjoy!

SP 2010: Developing for performance Part 2 – SPMonitoredScope

December 21st, 2010 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 2 (this article):
In this article I will talk briefly about what SPMonitoredScopes are and how you can utilize them in combination with your developer dashboard to get some stats and performance information about your custom applications.

SPMonitoredScope to track performance in your applications

The monitored scope (SPMonitoredScope) is a class you can use to monitor performance and resource usage in your applications by using it in a simple code block.

The pros about using the monitored scopes are of course that you can easily track down and find bottlenecks as well as do some initial performance monitoring while doing your development.

Using SPMonitoredScope

In order to use the SPMonitoredScope you’ll need to add a using statement for Microsoft.SharePoint.Utilities and then wrap your code in a statement like this:

using (new SPMonitoredScope("CallMethod1 Monitored Scope"))
{
    Controls.Add(new Literal {Text = "Awesomeness<br/>"});
}

You don’t need to add any more code than this in order for it to be hooked up.

See the results

So what now, what if I’ve added some monitored scopes to some of my classes – where can I see the results?

Answer: Open up your developer dashboard on the page where your code is executing and pow, you’ll see it right there:

Note: I’ve added three monitored scopes in my code, as seen below named CallMethod1,2,3
image

You can see that the CallMethod3 is the one dragging this page down in my particular case. Easy enough to keep track of the request time for your pages!

You can even nest your scopes

If you’ve got nested method calls and a bit more code (you’re likely to have that), you can of course nest your monitored scopes. There’s nothing to it really, you can instantiate new monitored scopes inside of a monitored scope:

using (new SPMonitoredScope("My Monitored Scope"))
{
    Controls.Add(new Literal { Text = "When the awesomeness is flying… " });
               
    using (new SPMonitoredScope("My Sub-Monitored Scope"))
    {
        Controls.Add(new Literal { Text = "there’s no stopping it! " });

        using (new SPMonitoredScope("My Sub-Sub-Monitored Scope"))
        {
            Controls.Add(new Literal { Text = "<br/>I’m three levels deep!" });
        }

        using (new SPMonitoredScope("Another deep scope"))
        {
            Controls.Add(new Literal { Text = "Rock and rumble, rock and rumble" });
        }
    }
}

Results: Nested scopes (My Monitored Scope)!
image

Limitations

The SPMonitoredScope is NOT available for Sandboxed solutions unfortunately, so this neat trick will not work if you’re planning on deploying to the sandbox.

Summary

This was a short introduction to the SPMonitoredScope class that you can utilize in SharePoint 2010 when doing custom development. The pros with using these monitored scopes is that you can easily track performance of your custom applications using the Developer Dashboard without even hooking up any debugger or external performance monitor to your servers – this is all done and visualized in the web browser upon displaying the Developer Dashboard.

This is a very easy trick to keep an eye out for performance bottlenecks in your applications for SP 2010.

Enjoy!

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.

Related articles in this article series

Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState

Part 1 (This article):
This is Part 1 of 5 where I will introduce you to the developer dashboard in SharePoint 2010. The reason for the developer dashboard being a key concept in your SharePoint development tasks is the quick and effective manner of which you can start looking for bottlenecks and problems in your installation without launching any additional tools.

SharePoint 2010 Developer Dashboard

The developer dashboard is a perfect tool for anyone who wants a quick way to access information about what goes on while rendering a page in SharePoint. It contains information about Web Parts, events, DB calls and a whole lot of nifty information.

Activating the Developer Dashboard

Developer Dashboard is a utility that is available in all SharePoint 2010 versions, and can be enabled in a few different ways:

  • PowerShell
  • STSADM.exe
  • SharePoint Object Model (API’s)

Using these different approaches is very simple; All you will need to do is use one of the aforementioned methods to activate the dashboards, as described here:

Activate the Developer Dashboard using PowerShell:

$devdash =
Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$devdash.DisplayLevel = ‘OnDemand’;
$devdash.TraceEnabled = $true;
$devdash.Update()


Activate the Developer Dashboard using STSADM.EXE

STSADM.EXE -o setproperty -pn developer-dashboard -pv ondemand

Activate the Developer Dashboard using the SharePoint Object Model

using Microsoft.SharePoint.Administration;

SPWebService svc = SPContext.Current.Site.WebApplication.WebService;
svc.DeveloperDashboardSettings.DisplayLevel =
    SPDeveloperDashboardLevel.Off;
svc.DeveloperDashboardSettings.Update();

Note that in the preceding samples I’ve used a property called "OnDemand". This can be set to the following values:

  • Off (Disables the Developer Dashboard)
  • On (Enables the Developer Dashboard)
  • OnDemand (Enables the Developer Dashboard upon request by clicking the icon in the upper right corner)

If the Developer Dashboard is set to OnDemand, this button appears in the top right corner just next to your login name:
image

As a side note, you can also enable Tracing for your developer dashboard to enable your dashboard to display the asp.net page trace. I will cover this a bit further down.

Reading the Developer Dashboard information

When you click the small icon in the top right corner, the Developer Dashboard will be opened and displayed at the bottom of your page.

Developer Dashboard example:
image

You can see that it has a Green border right now. That generally means it’s loading quick enough not to be a real problem. It can also render Yellow, which indicates that there’s a slight delay and then it could render a Red border which would mean you definitely need to look into it immediately!

So, what information can you read out of this?

Page Request to the left-hand side

You can read out the Page Request, and see what loads and how long it takes to load. This is perfect to use to track down heavy-loading apps or finding out what’s taking so long to render the page;
image

Web Server, Events, DB Queries, Service Calls, SPRequests, Web Part Events on the right-hand side

image

Dig deeper into the SQL DB queries by clicking on the link

If you’d like to get some more in-depth information about what query was shot away to the DB, click the hyperlink corresponding the query you want to find out about and you’ll see something like this;

image

Displaying ASP.NET Trace information

One thing that I absolutely love about this tool is the ability for the tool to enable Tracing (this should be enabled when you enable the Developer Dashboard using the SP Object Model or PowerShell by setting the following flag:

DeveloperDashboardSettings.TraceEnabled = true;

If you’ve done this, and you’ve got the Developer Dashboard enabled – you should see the following link in the bottom left area of the developer dashboard:
image

If you click it, you’ll see the full ASP.NET Page Trace like this (awesome, very very awesome):
image

The beauty about this is you don’t have to go and edit the web.config and enable tracing there – you just click this little button and it’s all done. I love it.

Developer Dashboard Visualizer – Extend your developer dashboard with diagrams

One of my friends Jaap Vossers wrote up a cool functionality to use in conjunction with the Developer Dashboard – Developer Dashboard Visualizer – which is a cool utility if you want to visualize what the rendering process looks like on your page.

If you’ve downloaded this awesome solution, you’ll see a new Site Collection feature that you’ll need to enable:
image

Once that’s done, next time you’ll visit the Developer Dashboard awesomeness it’ll look something like this:
image

Developer Dashboard activation as a Feature

My good friend Wictor Wilén wrote a quick and cool feature to ease the activation of the Developer Dashboard settings (find it here) which allows you to more easily change the settings of the developer dashboard without doing it by typing any scripts or code.

Once you’ve downloaded and installed the solution, you’ll find a new Farm feature that should be activated, which provides some functionality to Central Administration for administering the Dev Dashboard:
image

If you’ve deployed and got this feature activated, head on over to General Application Settings and you’ll see that you’ve got a new header called "Development Settings" containing a link to "Developer Dashboard Settings".

Click it and you’ll see this very awesome page that enables you to configure the Developer Dashboard without actually writing any code!

image

Summary

In this article you’ve read about the Developer Dashboard and how to enable it, and a few extra tips that you can download and install to make your experience with the Developer Dashboard even cooler.

This was part 1 in an article series talking about a few concepts we’ll need to understand in order to properly plan and design for performance in our SharePoint 2010 applications.

Stay tunes for parts 2-5.

Enjoy!