Tuesday, June 8, 2010

Increase the Performance of the web page

Hi All,

Here I am going to share about “Increase the Performance of the web page”.

Before start, I would like to share how and why I am writing this article now. Actually we have developed portal for one of our customer, who is running a business in Greece. The site is kind of online shopping portal. When our client has approached to us about this portal, our project analysis team felt; why should develop this portal as new one. Because in the market plenty of on-line shopping tools are available, just will buy and customize that and sell it out to the customer. As per it, they have decide to buy and bought it. As we all know, when we are buying a product it will be having plenty of extra features which is not required for user. Problem started here only. We have customized that third party tool. But performance issue becomes very big issue.

Our customer requirement is, page should load < 3s (less than three seconds). But system took to load home page 32s (thirty two seconds) it’s not at all acceptable right? L ya its true.

Writing a Web application with ASP.NET is unbelievably easy, many developers (include meJ) don't take the time to structure their applications for great performance.


In bellow, what are the steps I have followed to increase the page performance/loading time?
  • Caching
  • View state Compression
  •  Minimize HTTP Requests
  •  IIS settings enable (Static/ Dynamic contents compression)
  •  Put Stylesheets at the Top
  •  Put Scripts at the Bottom

Caching:
               When we talk about performance in asp.net, first we will think about caching concept only, so most of us know well about caching. So here I am not going to discus or write about caching.

View State Compression & Decompression:

Most of the times we will be fail to notice about our page render part in web application. How it’s been rendering and how the data are passing back to server while postback event fire.

Http is a stateless protocol. Hence the ‘page-state-information’ is not saved between postbacks. In ASP.NET, viewstate is the means of storing the state of server side controls between postbacks. It contains a snapshot of the contents of a page. The information is stored in HTML hidden fields.

The viewstate is quiet handy in most cases as it does a lot of work for you in saving the state of controls. However it comes with a cost. 

If your page contains a lot of controls holding a large amount of data, you can imagine the load when this data is transferred to and from the browser on each postback. It gradually increases the size of your page, thereby leading to performance issues. Well you can get around this problem by disabling viewstate for controls, where maintaining state is not required (EnableViewState=false). However, in scenarios, where maintaining the state of controls is required, compressing viewstate helps improve performance.

Compressing/Decompressing using GZipStream

The following system class is used for compressing view state.

using System.IO.Compression;


    ///
    /// Summary description for BasePage
    ///
    public class BasePage : Page
    {
        /////
        ///// This following method for compressing the viewstate values
        /////
        /////
data">
        /////
        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();
        }

        /////
 ///// This following method for decompressing the viewstate values             
 /////
        /////
        /////

        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();
        }

        ///
        /// This following method for save the viewstate values in compressed format
        ///
        ///
pageViewState">
        ///
        protected override void SavePageStateToPersistenceMedium(object pageViewState)
        {
            LosFormatter losformatter = new LosFormatter();
            StringWriter sw = new StringWriter();
            losformatter.Serialize(sw, pageViewState);
            string viewStateString = sw.ToString();
            byte[] b = Convert.FromBase64String(viewStateString);
            b = BasePage.Compress(b);
            ClientScript.RegisterHiddenField("__RAVIVIEWSTATE"Convert.ToBase64String(b));
        }


        ///
        /// This following method for Loading compressed viewstate values
        ///
        ///
        ///
        //// Deserialize view state
        protected override object LoadPageStateFromPersistenceMedium()
        {
            string custState = Request.Form["__RAVIVIEWSTATE"];
            byte[] b = Convert.FromBase64String(custState);
            b = BasePage.Decompress(b);
            LosFormatter losformatter = new LosFormatter();
            return losformatter.Deserialize(Convert.ToBase64String(b));
        }

 There you go!! Use these classes and hopefully your ViewState size will be reduced by 30-40%.

Test Case:
Case 1:
               Now run the web page without calling the above class. And copy the viewstate value into text file and save it(WithOutCompression.txt). Check the files size.(ex: 38 KB)

Case 2:
               Now run the web page with viewstate compressing mechanisam. Again copy the viewstate value into text file and save it(WithCompression.txt). Check the files size.(ex: 7 KB)
Minimize HTTP Requests
80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.
One way to reduce the number of components in the page is to simplify the page's design. But is there a way to build pages with richer content while also achieving fast response times? Here are some techniques for reducing the number of HTTP requests, while still supporting rich page designs.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.
Image maps combine multiple images into a single image. The overall size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be tedious and error prone. Using image maps for navigation is not accessible too, so it's not recommended.
Inline images use the data: URL scheme to embed the image data in the actual page. This can increase the size of your HTML document. Combining inline images into your (cached) stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages. Inline images are not yet supported across all major browsers.
Reducing the number of HTTP requests in your page is the place to start. This is the most important guideline for improving performance for first time visitors. As described in Tenni Theurer's blog post Browser Cache Usage - Exposed!, 40-60% of daily visitors to your site come in with an empty cache. Making your page fast for these first time visitors is key to a better user experience.

IIS 6.0 settings enable (Static/ Dynamic contents compression)
 Enabling compression on IIS 6.0 is a multi step process.

Step 1: Enable direct metabase edit  for in place editing of the metabase.xml file (which is otherwise locked).

Step 2: Enable static and dynamic compression on IIS 6.0

Conclusion:
 I hope this article was informative and I thank you for viewing it. Don’t consider only these many steps/ways are there to increases web page performance. Still there are plenty of options are there, developer should understand and analysis it.

Monday, June 7, 2010

Find browser window width & height

Hi all, here i am going to write a simple javascript method to find a window width and height.

JS Method:

function FindWindowSize() {
var myWidth = 0, myHeight = 0; //Initialize the local variable

if (typeof (window.innerWidth) == 'number') {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
alert('Width = ' + myWidth + ' Height = ' + myHeight);
}

Calling Place:

window.onload = alertSize;