Compressing viewstate improves performance

Source: Internet
Author: User
Tags website performance
[Translation] Improving Performance by compressing viewstate in Asp.net 2.0

Original article released on: 2007.03.08
Author: Bipin Joshi
Translation: webabcd

Introduction
Developers often worry about the performance of their web sites. Every developer wants to optimize the performance of their web sites. Viewstate is one of the many factors that affect your website performance. This article will provide you with a way to improve the performance by compressing viewstate.

What is viewstate?
Although this article does not focus on viewstate, let's simply discuss it. If you have read the HTML code generated by web form, you will find a hidden field named _ viewstate. Smart ASP. NET will persist the value of these controls to this hidden domain, which is very useful for saving the value of the controls during the process of round-trip to the server. However, viewstate may cause performance problems. Because viewstate must be transmitted between the server and the client, the network bandwidth traffic is increased.

To reduce viewstate, you can disable viewstate, that is, set the enableviewstate attribute of the control. If this attribute is set to false, the viewstate of the control is disabled. However, if there is no viewstate, you need to do the control state persistence work by yourself, which is a headache. Another method to reduce viewstate is described in this article, that is, compressing viewstate before transmission, so that viewstate data will be greatly reduced.

In ASP. NET 1.x, if we want to use the compression function, we need to write some code by ourselves. Currently,. NET 2.0 provides the system. Io. Compression namespace, which will simplify the implementation of the compression function. The gzipstream class in the system. Io. Compression namespace can process stream compression and decompression. Note that gzipstream can only work as a stream. The gzipstream class does not know how to compress viewstate. Therefore, we need to write some code to compress and decompress viewstate.

Develop viewstatehelper
Create a web site using Visual Studio, and add a class named viewstatehelper to the app_code folder. The namespace to be introduced at the top of the class file is as follows:

Using system. IO;
Using system. Io. compression;

The system. Io namespace provides stream classes, such as memorystream. The system. Io. Compression namespace provides the gzipstream class, which allows you to render data in GZIP format (RFC 1952 ).

Compressed Data
Now add a method named compress () as follows:

Public static byte [] compress (byte [] data)
{
Memorystream MS = new memorystream ();
Gzipstream stream = new gzipstream (MS, compressionmode. Compress );
Stream. Write (data, 0, Data. Length );
Stream. Close ();
Return Ms. toarray ();
}

This compress () static method receives and compresses a variable of the byte array type and returns a compressed byte array. It first refers to a memorystream class, which is used to present the stream in the memory. Then, create a gzipstream object using the memorystream and compression mode parameters. You can replace memorystream with any stream type. The compressed data is written into the stream. The write () method of the gzipstream class will receive a variable of the byte array type, compress it, and write it into the stream (in our example, memorystream ). After writing, gzipstream is disabled. Finally, the toarray () method of memorystream converts the stream data to the byte array.

Extract data
To decompress the data, we need to add another method named decompress (). The key code is as follows:

Public static byte [] decompress (byte [] data)
{
Memorystream MS = new memorystream ();
Ms. Write (data, 0, Data. Length );
Ms. Position = 0;
Gzipstream stream = new gzipstream (MS, compressionmode. Decompress );
Memorystream temp = new memorystream ();
Byte [] buffer = new byte [1024];
While (true)
{
Int READ = stream. Read (buffer, 0, buffer. Length );
If (read <= 0)
{
Break;
}
Else
{
Temp. Write (buffer, 0, buffer. Length );
}
}
Stream. Close ();
Return temp. toarray ();
}

This decompress () static method receives a compressed byte array and returns an unzipped byte array. First, it creates a memorystream object and writes a compressed byte array. The stream is then provided as a parameter to the gzipstream constructor. Note that the compression mode is decompress. The decompressed data also needs to be saved somewhere, so another memorystream object created next is used for this purpose. Then we use a while loop to read and extract the extracted data from gzipstream, each of which is 1024 bytes. Then the data is written into memorystream. Finally, gzipstream is disabled, and the extracted content is returned as a byte array.

Create a web form
Open a Web form, drag a sqldatasource control to it, and configure it so that it can read the records of the MERs table from the northwind database.

Drag a gridview control and set its performanceid attribute to the ID of the configured sqldatasource control. Make sure that running this web form is the expected result. The example is as follows:

Custom viewstate serialization and deserialization
You don't need to worry about viewstate serialization and deserialization, because these are automatic. However, we need to compress viewstate, so we need to customize its serialization and deserialization. The page base class has two virtual Methods: savepagestatetopersistencemedium () and loadpagestatefrompersistencemedium (). They allow you to customize the serialization and deserialization of viewstate respectively.

First, rewrite the savepagestatetopersistencemedium () method in the post code of the web form. In this method, you compress the viewstate and store it in a hidden domain. The Code is as follows:

Protected override void savepagestatetopersistencemedium (object state)
{
Losformatter formatter = new losformatter ();
Stringwriter writer = new stringwriter ();
Formatter. serialize (writer, State );
String viewstate = writer. tostring ();
Byte [] DATA = convert. frombase64string (viewstate );
Byte [] compresseddata = viewstatehelper. Compress (data );
String STR = convert. tobase64string (compresseddata );
Clientscript. registerhiddenfield ("_ myviewstate", STR );
}

The savepagestatetopersistencemedium () method receives a viewstate object. Create a losformatter object in this method. The losformatter class allows you to serialize and deserialize data in viewstate. The serialize () method of the losformatter class receives two parameters: a stream and an object. The result is to serialize the object to the stream. In our example, viewstate is serialized to stringwriter. The tostring () method of stringwriter returns a string used to render viewstate data. This string is in base64 format (stored in viewstate in ASP. NET). We need to convert it into the desired format. The frombase64string () method of the convert class can do this. The frombase64string () method returns a byte array of data, and then uses the compress () method of our viewstatehelper class to compress it. Then, use the tobase64string () method of the convert class to convert the compressed data to the base64 format. Finally, we use clientscript's registerhiddenfield () method to register the compressed base64 format data to a hidden domain named _ myviewstate.

This is how we compress viewstate. Another equally important task is decompression. We can rewrite loadpagestatefrompersistencemedium () to implement this function. The Code is as follows:

Protected override object loadpagestatefrompersistencemedium ()
{
String viewstate = request. Form ["_ myviewstate"];
Byte [] DATA = convert. frombase64string (viewstate );
Byte [] uncompresseddata =
Viewstatehelper. Decompress (data );
String STR = convert. tobase64string (uncompresseddata );
Losformatter formatter = new losformatter ();
Return formatter. deserialize (STR );
}

This method first reads the value of the hidden field of _ myviewstate, Which is compressed viewstate in base64 format. In order to decompress it, your first step is to convert it into a byte array, which we will do through the frombase64string () method of the convert class. Next we use the decompress () method of the viewstatehelper class to decompress the data. Use the tobase64string () method of the convert class to convert the decompressed data to a base64 string. Finally, the viewstate after the losformatter object is deserialized and decompressed

The above is the whole content of compressing and compressing viewstate. After my actual tests in this example, we found that the size of the uncompressed viewstate is 13,568 bytes, and the size of the compressed viewstate is 5,932 bytes. This is very useful for improving performance. What do you say?

Summary
From this article, you learned how to compress viewstate to improve the performance of your web site. The gzipstream class provides a ready method to compress your data into GZIP format. The compressed data must be saved by overwriting the savepagestatetopersistencemedium () method of the page base class. Similarly, after reading viewstate, We need to rewrite loadpagestatefrompersistencemedium () to decompress the data.

Note: IIS6 supports built-in gzip compression, and both IE6 and Firefox support client gzip. To enable the gzip compression function of IIS, please google

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.