Practical Approaches for Optimizing Website Performance

Optimizing website performance is a challenging task. Websites are composed of many moving parts - both on the client and on the server - and optimizing performance requires a multi-faceted approach that addresses potential problems in all moving parts. Performance bottlenecks are caused by an array of problems, from browser mechanics to server configuration, and a clear understanding of how to address these problems will provide AJAX ASP.NET developers with the tools necessary to make any website faster.

What Does It Mean to Optimize Performance?
Before any discussion about improving website performance begins, it's very important to ensure a clear understanding of what "performance" means in this context. With websites in particular, it's easy to confuse the terms "performance" and "scale." Both are important, but each focuses on a separate aspect of building a high-quality website.

Performance, as we are using it in this context, refers to the speed or responsiveness of a website. Minimizing page load times, making operations with data grid controls fast, and in general reducing the amount of time your user spends waiting on your site all fall under the umbrella of performance. If you have a client or boss who wants sub-second page load times, they are asking you to deliver performance.

Scale, meanwhile, deals with the idea of ensuring that performance is maintained as more people use your site. A website might load in less than a second when five people are using it, but when 5,000 people start hitting it, a site will start to slow down, or worse, if good scalability techniques are not used. Therefore, poor scalability will lead to poor performance as your site's usage grows, so it's important to address both scalability and performance for a high-quality site. There are many unique techniques for addressing scalability, and some actually sacrifice performance in exchange for better handling of load.

Fortunately, while the techniques explored in this article focus primarily on making websites load faster and feel more responsive, most also have a beneficial impact on scalability.

How Do You Measure Performance?
In order to determine if any technique has a positive or negative effect on performance, you must know how to measure performance. No performance improving technique is a silver bullet and, depending on the infrastructure and the geographic distribution of site users, different techniques will yield varying degrees of improvement.

The key performance factor generally measured is page load time, either of an initial load or a load that occurs as the result of a page action, such as clicking a button. Basic testing can be performed with free tools like Firebug in Firefox or Fiddler. These tools will clearly show you important information about factors that impact page performance, and they will also provide a basic indication of total page load time, though these tools generally fail to capture the time a page takes to fully initialize in a browser. There are also free tools like Google's Page Speed plug-in for Firefox and Yahoo's YSlow plug-in that try to analyze your site pages and provide guidance for improving performance. All of these tools are good for rough, relative performance measurements, but the results are not accurate measures of performance from an end user's perspective.

To perform more accurate testing, measurements must account for the variables that impact your users, such as latency. If your site is accessed by users around the world, and you have a single server in Texas, performance will be perceived very differently by users in the U.S. versus users in Asia. Connection speeds also have a big impact on perceived site performance. Gathering measurements that account for these variables is difficult to do with local testing, but fortunately there are many services that can supply performance measurements using globally distributed testing servers, such as Gomez. In fact, Gomez offers a free instant testing tool you can use to measure your site performance as experienced by a computer in New York.

Performance testing does not require simulating load, or the process of testing your site under the simulated condition of many people hitting it at once. When you introduce load, you begin to test the scalability of a website and not the "pure" performance. Scalability tests are important, but when your focus is strictly improving site performance, load testing should not be used when collecting measurements.

How Do You Improve Performance?
Generally speaking, there are two key ways to improve performance in a website:

  1. Reduce the number of bits that must be downloaded to load a page
  2. Reduce the number of HTTP requests a page requires to load

If you can optimize these two factors, your site performance will improve.

Save the Tubes: Reducing Bits
One of the easiest ways to improve site performance is to reduce the number of bits your users must download to load pages. Fundamentally, all web pages require users to download bits from a server (in the form of HTML, CSS, JavaScript, images, etc.) that are then processed by the browser and ultimately displayed to the user in the form of your page. Reducing those bits reduces the time your users must wait to view your page.

There are several easy techniques you can use to begin reducing the bytes your users must download and improve page load times:

1. Compress HTTP Traffic
When a user requests an ASP.NET page, much of what the server returns is "text" data - HTML, CSS, and JavaScript. This type of data compresses very well, so applying compression on the server before the data is transmitted to a user's browser can significantly reduce the number of bytes that must be sent over the Internet "tubes." When the compressed data arrives at the user's computer, browsers have the built-in ability to decompress the received info and display it to the user.

The beauty of this technique is that it is extremely transparent. In most cases, you can apply HTTP compression to your site without making any changes to your code. The latest version of Microsoft's IIS web server provides built-in support for applying HTTP compression to basic communication between a web server and a browser, and third-party tools can be easily added to ASP.NET websites to compress "advanced" asynchronous AJAX and Web Service data (data which IIS7 does not compress).

2. Compress ViewState
Related to compressing HTTP traffic - at least in ASP.NET websites - is compressing ViewState. Many ASP.NET developers have a love-hate relationship with Microsoft's helpful "state manager" for the web, but regardless of your feelings, ViewState is something that must be managed. Even when ViewState is disabled in an ASP.NET WebForms application, ControlState, which cannot be disabled, can still fill the ViewState hidden field with data.

One way to reduce the impact of ViewState on your page is to compress it. By default, the ugly value stored in the ViewState field is serialized, but it is not compressed. There are methods you can override, though, that make it easy to compress and decompress ViewState on the fly. For example, with a few lines of code you can override the SavePageStateToPersistenceMedium page method and change the way ViewState is saved:

protected override void SavePageStateToPersistenceMedium(object state)
{
ObjectStateFormatter osf = new ObjectStateFormatter();
string viewStateStr = osf.Serialize(state);

byte[] bytes = System.Convert.FromBase64String(viewStateStr);

bytes = ViewStateCompressor.Compress(bytes);
string vStateStr = System.Convert.ToBase64String(bytes);
ClientScript.RegisterHiddenField("__VSTATE", vStateStr);
}

The process is simply inversed when ViewState is read on a page PostBack. This example also makes use of a "ViewStateCompressor" class, which is a simple class that provides your GZip compression and decompression logic. There are tools from third-party providers, such as Telerik's RadCompression, that also enable you to apply compression to ViewState without writing any code or making any changes to your pages.

Using ViewState compression in conjunction with HTTP compression is also a good idea, especially if you have a large amount of ViewState. While a server applies HTTP compression to the data it sends to a browser, a browser does not compress data sent back to the server when a page POSTs back. That means uncompressed ViewState must be uploaded by your users when posting a page. If you use ViewState compression, though, users benefit from this compression on both the initial page load and during POSTs back to the server.

3. Reduce HTML
Less markup on your page results in less data that your users must download, which ultimately results in a faster page load. Before you write this off as being too obvious, think about the ways you may be "overusing" HTML today. A common problem among web developers, and even among some ASP.NET UI components, is using HTML tables and in-line styles to define UI elements. Take, for example, the HTML produced by the default menu control available with ASP.NET (simplified slightly for clarity):

<table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td style="white-space:nowrap;width:100%;">Book 0</td></tr>
</table>
</td></tr>
</table>

This code uses nested HTML tables to produce the menu's layout, which is a "heavy" use of HTML. A better solution, and a way to reduce the HTML on your page, is to use semantic HTML. Semantic HTML is markup that accurately describes its content. For example, a TABLE tag should contain tabular data. A UL tag should contain a list of items. Leveraging semantic HTML in combination with the power of CSS makes it possible to significantly reduce a page's HTML. A semantic rendering of our previous example reduces the required markup by a staggering 83%:

<ul class="menu">
<li>Book 0</li>
</ul>

Meanwhile, you can further reduce the bits your users are downloading by "minifying" your CSS and JavaScript. Minifying is similar to compression, but it does involve making changes to your code (usually done as part of a build process). When you minify JavaScript and CSS, all unnecessary characters and comments are removed, producing files that are very cryptic, but very small. Tools like YUI Compressor and JSMin are popular choices for JavaScript minification, and according to Yahoo minification reduces JavaScript size 21 percent on average (an additional 5 percent if you're already using HTTP compression). Like HTTP compression, minification is a transparent process that is easy to apply to existing code without introducing unexpected bugs.

4. Use Client-Side Rendering
This technique is different from the others covered up to this point and it requires a more fundamental change in your approach to web development. Where compression and minification are relatively transparent and easy to apply to existing code, transitioning from pages that render on the server to pages that can render in the browser requires new development habits and tools. Adopting these methodologies, though, is critical to making your standards-based web applications feel as responsive as desktop or RIA applications.

The general change in approach is this: rather than rendering a page's HTML on the server and then sending all of the data and all of the HTML over the wire to a client, instead you only send data over the wire (usually in JavaScript Object Notation, or JSON) and then use JavaScript in the browser to build your HTML layout. Where previous techniques we examined show you how to reduce the HTML sent over the wire, this technique eliminates it.

Adopting this approach without the assistance of any tools is very challenging, so developers usually leverage third-party tools or open source frameworks, such as jQuery, to assist with the processing of JSON on the client. With the proper assistance, developers can move away from the heavy PostBack model traditionally found in ASP.NET WebForms applications and begin leveraging web services and JSON to produce lightning-fast web experiences. The next version of ASP.NET will also provide support for client-side controls, making it easier than ever to completely remove HTML from client/server communication.

This approach is not without its caveats. Since JavaScript is required to display client-side controls, search engine crawlers cannot see content rendered on a page in this way. It's important to detect the capabilities of the client accessing your site and ensure the proper rendering technique is used.
Ask Less: Reducing Requests
What is the primary performance bottleneck in browsers today? Browser request limits. With dial-up connections a thing of the past for most users and PCs more powerful than ever before, waiting on the browser to request and download all the "pieces" of your page is usually what requires the most time for modern websites. According to Yahoo's Exceptional Performance Team, 80 to 90 percent of end-user response time is spent waiting for these pieces.

Per the HTTP/1.1 specification, most browsers limit parallel requests to two per hostname, and six total (for all tabs and hostnames). Think about that. Assuming you're not using any of the techniques discussed later, that means every image, every JavaScript file, and every CSS file can only be downloaded two at a time. The limits were originally created in the days of weaker computers and slower connections to prevent systems from being overloaded, but today they represent a huge barrier to site performance.

Here are some techniques you can implement in your site that will not only reduce requests, but also "trick" browsers in to allowing you to use more than two parallel requests.

CSS Sprites
Sprites find their roots in early video games, where processor-strapped developers needed a technique to optimize performance. As processing power improved, video games had less use for this optimization technique, but web developers now leverage it as a way to reduce requests to the server.

Put simply, CSS sprites are essentially a collection of images that have been combined into a single, larger image file. The images can be several states (such as "normal" and "mouse over") of the same image, a collection of unique images (such as toolbar icons), or a combination of both. The "magic" of CSS sprites is the use of CSS background positioning to only display the portion of the large, single image file where a smaller image should be shown.

The main advantage of sprites is that they significantly reduce requests to the server. Think about all of the images your website downloads today when it loads. Each of those images represents a request to the server, and with the default two-request limit, images can quickly clog the request queue. By using sprites, you could in theory replace all images in your site with a single image file, though this is not the way sprites are commonly used. While the resulting sprites are larger files, modern computers with broadband connections are much better at downloading fewer larger files than hundreds of small files, due to the overhead and latency of processing HTTP GETs.

The advantages of CSS sprites are clear, but they can be hard to create from scratch. Several online tools can help you transform individual images into sprites, and a quick search for "css sprite generator" should help you discover the popular options. Further, when evaluating UI components to use in your ASP.NET websites, make sure the controls use CSS sprites in their own rendering.

Script Combining
If CSS sprites are used to combine images, then script combining is the related technique for combining CSS and JavaScript files. The main advantage of script combining is the same as CSS sprites: fewer files to download, which means fewer requests and a faster loading page. Script combining can be done manually, but there are many tools today for ASP.NET developers that will do JavaScript and CSS file combining on the fly, eliminating the need to constantly re-create combined versions of your resource files as you modify them.

With .NET 3.5 SP1, the ScriptManager control that ships with ASP.NET AJAX can do automatic JavaScript combining. To leverage that feature, use the new CompositeScript block, like this:

<asp:ScriptManager runat="server" ID="ScriptManager1">
<CompositeScript>
<Scripts>
<asp:ScriptReference Name="MicrosoftAjax.js" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.js" />
</Scripts>
</CompositeScript>
</asp:ScriptManager>

The ScriptManager supports combining both scripts found in the ASP.NET AJAX assemblies and your own external scripts. By default, ASP.NET AJAX makes 11 separate requests for framework scripts when you use a ScriptManager control, so using combining for these scripts alone will shave 10 requests off your initial page load.

Varying Hostnames (and CDNs)
This technique will not help you reduce requests, but it will enable you to work around the browsers default two-request limit and potentially allow your page to download up to four times as many files at one time. The solution is rooted in the fact that a browser enforces the two-request limit based on hostname, such as "www.yoursite.com." To the browser, hostnames like "www.yoursite.com," "images.yoursite.com," and "images2.yoursite.com" are all unique and each can process two requests at once when your page loads. Fully leveraged, you can effectively quadruple your site's allowed bandwidth.

When you vary hostnames, you can have the resource URLs point to physically separate locations, or you can have them all route to the same location via DNS routing. The browser does not check to ensure the each hostname has a unique IP address. You can also use something called a Content Delivery Network (CDN) to further improve performance by placing resources, such as videos and images, geographically closer to your users, thus reducing latency and improving download performance. Since a CDN also lives on a separate hostname from your site, it inherently helps work around the browser request limit, too.

Load JavaScript Last (When You Can)
This last technique also does not help you reduce requests, nor does it help you work around the browser request limit, but it does help your page process requests as quickly as possible. The problem is that browsers will block additional requests if JavaScript is being downloaded, regardless of browser request limits and hostnames. Browsers do this because the JavaScript being downloaded could have an effect on page layout, and waiting prevents unnecessary and expensive redraws of the page as it loads.

Moving JavaScript to the bottom of your page enables all other requests to process quickly, which will make your page appear to load more quickly. The browser will begin rendering faster if it's not waiting on all of your JavaScript to load at the top of your page.

Of course, not all scripts can be moved to the bottom of a page. If the script is a library, such as jQuery, that is required for other components on the page to render, it must be loaded early in the page lifecycle. As a general rule of thumb, any script that is not involved in manipulating the initial layout of your page can (and should) be placed at the bottom of your page.

Measuring Tips for ASP.NET Developers
Now that you're armed with an arsenal of new techniques to apply to your websites to begin improving performance, you're likely to want to gather some measurements. We've already discussed the general approach for measuring performance, but there are some specific "tips and tricks" for ASP.NET developers that can help you gather accurate results:

It may seem obvious that you shouldn't use Cassini to gather performance data for your site, but during active development with Visual Studio it can be easy to forget the impact this lightweight web server has on performance. In local tests conducted on a simple ASP.NET page, pages served by Cassini on average take 20 percent to 50 percent longer to load than IIS. Before you spend days trying to get a page to load in less than a second in your development environment, make sure you test the page in a real web server and measure real performance.

Perhaps similarly obvious to not testing performance with Cassini, most ASP.NET developers know that leaving "debug=false" in web.config negatively impacts performance. But do you know how much it impacts load time performance? In local tests, the simple act of setting "debug=false" improves average page load time by 27 percent.

Finally, it's important to make sure your tests differentiate between a "primed" and "unprimed" browser cache. Many of the performance bottlenecks examined in this article are hard to observe on a "primed" cache, because the browser will load images, scripts, and resources from a local cache instead of trying to pull the data from the server. Clearly, most users will benefit from this caching after their initial visit to your site, so it's important that you measure both primed and unprimed scenarios to understand how the performance experience differs.

Conclusion
Many of the techniques outlined in this article are easy to implement. Spending a few hours testing these techniques and measuring the results will help most modern, interactive websites improve performance and responsiveness. Optimizing performance can be a challenging task, but armed with these eight techniques AJAX ASP.NET developers can easily begin the process.

Resources

© 2008 SYS-CON Media