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:
If you can optimize these two factors, your site performance will improve.
Save the Tubes: Reducing Bits
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
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);
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">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td style="white-space:nowrap;width:100%;">Book 0</td></tr>
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%:
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.
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.
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.
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.
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.
<asp:ScriptManager runat="server" ID="ScriptManager1">
<asp:ScriptReference Name="MicrosoftAjax.js" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.js" />
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.
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.
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.