In my previous article 7 Easy-to-Apply Tips to Improve Your Web Site Performance, I described methods to achieve better client-side performance. The conclusion of the article was: “The most important and effective way to improve web site performance is to make fewer HTTP Requests.”
Since browsers only are able to download two components on parallel per hostname, and every HTTP request has an average round-trip latency of 0.2 seconds, that causes a 2 second latency alone, if the site is loading 20 items, regardless of whether they are style sheets, images or scripts. (On an average broadband connection with a browser capable of downloading two components at a time).
Since browsers spend approximately 80% of the time fetching external components such as scripts, style sheets and images. Reducing the number of HTTP requests has the biggest impact on improving website performance. Moreover, it is the easiest way to make a performance improvement.
This article focuses on ways of minimizing HTTP Requests to maximize web site performance.
More...
Currently rated 3.5 by 17 people
- Currently 3.470588/5 Stars.
- 1
- 2
- 3
- 4
- 5
Internet Applications with Web 2.0 features make heavy use of JavaScript. As rich web applications are being built with larger JavaScript, the need for JavaScript compression to keep bandwidth and page load times as small as possible by decreasing the size of the files served is becoming more important.
CompressJavascript.com takes your JavaScript code and compresses it by removing comments, whitespace, line feeds, and by shortening function parameters and variable names. This will reduce the script size, and may help your pages load faster and reduce bandwidth consumption.
Currently rated 4.9 by 7 people
- Currently 4.857143/5 Stars.
- 1
- 2
- 3
- 4
- 5
ViewState is the built-in structure for automatically retaining values between multiple requests for the same page in ASP.NET. In other words, ViewState technology saves/restores page state between postbacks. On the other hand, this technology comes with an overhead that affects performance especially during page load since the state data is maintained in a hidden field.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJLTMzMTY4NDI5ZGRrYY+UdQNeb33gRiGcw2LoiMHduA==" />
Reducing ViewState Size
We can completely disable viewstate by setting EnableViewState to false in the page directive but you need extra programming effort for you to take care of the page state. It is a good idea to disable ViewState for the controls that do not actually need it such as Literals and Labels by setting EnableViewState to false. But this do not entirely solve the problem.
Compressing ViewState
ASP.NET 2.0 comes with the System.IO.Compression namespace, which contains classes with functionality to compress/decompress streams. In ASP.NET 1.1, developers must use third party compression tools such as ICSharpCode.SharpZipLib to compress viewstate.
Compressing/Decompressing using GZipStream
The following class contains two methods for compressing and decompressing a stream.
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;
public static class CompressViewState
{
public static byte[] Compress(byte[] data)
{
MemoryStream output = new MemoryStream();
GZipStream gzip = new GZipStream(output,
CompressionMode.Compress, true);
gzip.Write(data, 0, data.Length);
gzip.Close();
return output.ToArray();
}
public static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream();
input.Write(data, 0, data.Length);
input.Position = 0;
GZipStream gzip = new GZipStream(input,
CompressionMode.Decompress, true);
MemoryStream output = new MemoryStream();
byte[] buff = new byte[64];
int read = -1;
read = gzip.Read(buff, 0, buff.Length);
while (read > 0)
{
output.Write(buff, 0, read);
read = gzip.Read(buff, 0, buff.Length);
}
gzip.Close();
return output.ToArray();
}
}
You need to save this class in a .cs file in the App_Code directory.
Utilizing the CompressViewState Class
In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.
The folowing code creates a BasePage class which inherits from System.Web.UI.Page, and web pages using the following Base Page class as the base class utilizes ViewState compression. The BasePage class adds an additional hidden field __COMPRESSEDVIEWSTATE, to store the compressed ViewState.
using System;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Configuration;
using System.Threading;
using System.Globalization;
using System.Text;
public abstract class BasePage : System.Web.UI.Page
{
private ObjectStateFormatter _formatter =
new ObjectStateFormatter();
protected override void
SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
Convert.ToBase64String(
CompressViewState.Compress(viewStateArray)));
}
protected override object
LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = CompressViewState.Decompress(bytes);
return _formatter.Deserialize(
Convert.ToBase64String(bytes));
}
}
Demo
Demo project contains two web pages. You may compare the compression performance using the demo project.
Download the viewstate compression demo VS2005 project.
An online demo web page without viewstate compression.
An online demo web page with viewstate compression.
If you view the HTML of the page with viewstate compression, the __VIEWSTATE field is empty, while our __COMPRESSEDVIEWSTATE field contains the compressed ViewState, encoded in Base64.
ViewState Compression Performance
After few tests using the demo project, ViewState size is reduces by 40 - 60% resulting shorter response times for users and less bandwidth need for site owners.
Compression, decompressing, encoding and decoding data is a quite heavy work for the server so while you are saving from bandwidth and offering shorter response times for users, you are having a performance hit on the server's hardware.
Currently rated 5.0 by 2 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5
When developing Web applications with ASP.NET, you sometimes need to access data which is shared among users again and again throughout the life of the application.
If you want to share a value or an object instance between all sessions, you typically use the Application object. However, a better alternative to Application object is a static property defined in a class. Static properties maintain their values throughout the Application. So they work like the Application object.
Storing and reading a static value is faster when we compare it with the Application object because static variables do not need to look-up in a collection when you refer to them and you do not need to cast from object to a specific type.
The key reason that the Application object exists in ASP.NET is for compatibility with classic ASP code to allow easy migration of existing applications to ASP.NET.
Currently rated 5.0 by 3 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5
.Net provides several different ways to extract integers from strings. In this article, I will present the differences between Parse, TryParse and ConvertTo.
Parse: This function takes a string and tries to extract an integer from it and returns the integer. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException. Finally, if the string value is null, it throws ArgumentNullException.
Int32 intValue = Int32.Parse(str);
Convert: This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException.
Int32 intValue = Convert.ToInt32(str);
TryParse: This function is new in .Net 2.0. Since exception handling is very slow, TryParse function returns a boolean indicating if it was able to successfully parse a number instead of throwing an exception. Therefore, you have to pass into TryParse both the string to be parsed and an out parameter to fill in. Using the TryParse static method, you can avoid the exception and ambiguous result when the string is null.
bool isParsed = Int32.TryParse(str, out intValue);
Examples:
string str1 = "1234";
string str2 = "1234.65";
string str3 = null;
string str4 = "999999999999999999999999999999999999999999";
int intValue;
bool isParsed;
intValue= Int32.Parse(str1); //1234
intValue= Int32.Parse(str2); //throws FormatException
intValue= Int32.Parse(str3); //throws ArgumentNullException
intValue= Int32.Parse(str4); //throws OverflowException
intValue= Convert.ToInt32(str1); //1234
intValue= Convert.ToInt32(str2); //throws FormatException
intValue= Convert.ToInt32(str3); //0
intValue= Convert.ToInt32(str4); //throws OverflowException
isParsed= Int32.TryParse(str1, out intValue); //isParsed=true 1234
isParsed= Int32.TryParse(str2, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str3, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str4, out intValue); //isParsed=false 0
Currently rated 5.0 by 2 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5
A lot of articles have been written on website performance optimization lately but I want to share my hands-on-experience and important articles on the subject.
There are two types of performance:
- Server Performance
- Perceived Performance
Server Performance is associated with the number requests that a server can handle at a time and the time needed to process these requests. On high volume websites, since it determines the number of users a machine can serve before additional server is needed, this performance aspect is very important.
Perceived Performance is the speed of websites in visitors’ perspective. Even if the server performance is high, a site may appear slow to a visitor because of slow client-side performance.
This article focuses perceived performance tuning by supplying reasons for poor client-side performance and details out how we can achieve better client-side performance.
1. Make Fewer HTTP Requests
A dedicated team focused on quantifying and improving the performance of Yahoo! Products worldwide conducted experiments to learn more about optimizing web page performance. They discovered that popular sites spend between 5% and 38% of the time downloading the HTML document. The other 62% to 95% of the time is spent making HTTP requests to get components in the HTML document.
Each bar represents a specific component requested by the browser - Only 10% of 2.4 seconds is spent for downloading the html of Yahoo.com
Since browsers only are able to download two components on parallel per hostname, and every HTTP request has an average round-trip latency of 0.2 seconds, that causes a 2 second latency alone, if the site is loading 20 items, regardless of whether they are style sheets, images or scripts. (on an average broadband connection with a browser capable of downloading two components at a time).
Since browsers spend approximately 80% of the time fetching external components such as scripts, style sheets and images. Reducing the number of HTTP requests has the biggest impact on improving website performance. Moreover, it is the easiest way to make a performance improvement.
UPDATE
How To: Minimize HTTP Requests – The Most Important Guideline for Improving Web Site Performance article focuses on ways of minimizing HTTP Requests to maximize web site performance.
2. Enforce Caching
If you examine the preferences dialog of any modern Web browser (like Internet Explorer, Safari or Mozilla), you’ll probably notice a cache setting. This lets you set a section of your computer’s hard disk to store copies of web pages, images and media for faster browsing.
This cache is especially useful when users hit the back button or click a link to see a page they’ve just looked at. Also, if navigation images throughout a site are the same, they’ll be served from browser's cache.
Internet Explorer Cache Settings
Web caching is useful for three important reasons:
- Reduce user-perceived Web-site delays,
- Reduce network bandwidth usage,
- Reduce server loads.
The Yahoo! Performance Team conducted another experiment to understand the difference between an empty cache (browser requests all the components to load the page) and full cache (most of the components are found in the disk to load the page and the HTTP requests corresponding to these components are avoided).
Loading Yahoo.com with full cache
Loading with an empty cache took 2.4 while loading with a full cache took 0.9 seconds. The full cache page view had 90% fewer HTTP requests and 83% fewer bytes to download than the empty cache page view.
3. Use HTTP Compression
The time it takes to transfer an HTTP request and response across the network can be significantly reduced by making fewer http requests. On the other hand, the end-user's bandwidth speed, Internet service providers are beyond the control of the development team. However compression reduces response times by reducing the size of the HTTP response.
In the case of HTTP compression, a standard gzip or deflate encoding method is applied to the payload of an HTTP response, significantly compressing the resource before it is transported across the web.
HTTP Compression is implemented on the server side as module which applies gzip algorithm to responses as the server sends them out. Any text based content such as static HTML content, style sheets, JavaScript. It is usually possible to cache the static content in order to avoid repeatedly compressing the same file. On the other hand, dynamic content such as .asp, .aspx, .php files must be recompressed before served. This means that there is trade off to be considered between processor utilization and payload reduction.
If the primary goal is bandwidth savings, the strategy should be to compress all text-based output. Ideally, this should include static text files (such as HTML and CSS) and files that produce output in text media MIME types (such as ASP and ASP.NET files), as well as files that are text based but of another media type (such as external JavaScript files).
Bloggingdeveloper.com utilizes gzip compression. 74% bandwidth is saved by compression.
4. Increase the Number of Parallel Requests
As I mentioned earlier, browsers are able to download two or four components on parallel per hostname. So we may increase the number of parallel downloads by using additional aliases such as images.bloggingdeveloper.com. According to the results of experiments conducted by Yahoo! Performance Team, using too many hostnames increases the amount of simultaneous HTTP requests but it will also increase the amount of DNS requests which affects the performance negatively. The Performance Team mentioned a strong balance between the number of parallel HTTP requests and required DNS requests to be performed of 2 to 4 hostnames. For higher number of hostnames, you may negatively affect the performance.
5. Place StyleSheets into the Header
Web developers that care about performance want browser to load whatever content it has as soon as possible. This fact is especially important for pages with a lot of content and for users with slow Internet connections. When the browser loads the page progressively the header, the logo, the navigation components serve as visual feedback for the user.
When we place style sheets near the bottom part of the html, most browsers stop rendering to avoid redrawing elements of the page if their styles change.
6. Put Scripts to the end of Document
Unlike StyleSheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all StyleSheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames.
7. Make JavaScript and CSS External
Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number of HTTP requests.
Additional Reading
Browser Cache Usage – Exposed! by Tenni Theurer
What the 80/20 Rule Tells Us about Reducing HTTP Requests – by Tenni Theurer
Maximizing Parallel Downloads in the Carpool Lane - by Tenni Theurer
Currently rated 5.0 by 4 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5