Brief discussion on the viewstate of optimizing ASP.net application performance

Source: Internet
Author: User
Asp.net| Performance | optimization

If you have the habit of viewing the HTML source code of the current browsing page in IE, you may often see code snippets similar to the following:

<input type= "hidden" name= __viewstate "value=" DDWTMZU5NZUYMTQ1O3Q8O2W8ATWWPJS+O2W8DDW7BDXPPDA+OZ47BDX0PDTSPG
......

Smart you will certainly ask, what is this? What's the effect? What is the relationship between it and this article? You reader, and listen to me slowly.

In fact, this is the characteristic performance of MS in asp.net application viewstate technology. In order for the page to still read the original state data of the server control after postback, the ViewState technology is used in asp.net, and the ViewState technology is essentially using a default name of "__ ViewState's Hidden type form field to save and pass data (the data is serialized BASE64 encoded string values that are saved before the method Page.savepagestatetopersistencemedium output, and loaded by Page.loadpagestatefrompersistencemedium). Although we can easily disable the roundtrip delivery of this data through three levels:

The machine level sets <pages enableviewstatemac= ' false '/> in Machine.config
The application level sets <pages enableviewstatemac= ' false '/> in the Web Applicatin web.config
Single page level set <% @Page enableviewstatemac= ' false '%> in this page or set Page.enableviewstatemac = False by code;

However, if we can completely disable the ViewState to solve the data transmission burden and no side effects, then the MS Architects will not be silly to such a cute point (what does it take to leave the optional stuff?) , because we often can not easily disable to solve the problem of transmission burden, so we can only make another path to the network in the transmission volume as small as possible, so, compressed into our preferred. As long as we overload the Page class Savepagestatetopersistencemedium () method and the LoadPageStateFromPersistenceMedium () method, and in the overloaded method of data compression and decompression processing can be. Open source project SharpZipLib provided by the class Gzipinputstream and gzipoutputstream into our vision, in order to facilitate, may wish to write a class Compressionhelper, the code is as follows:

1using System.IO;
2using ICSharpCode.SharpZipLib.GZip;
3
4namespace ycweb.components
5{
6/**////<summary>
7///Summary description for Compressionhelper.
8///</summary>
9 public class Compressionhelper
10 {
One public Compressionhelper ()
12 {
13//
//Todo:add constructor logic here
15//
16}
17
/**////<summary>
19///Compressed data
///</summary>
///<param name= "Data" > byte array to be compressed </param>
///<returns> Compressed byte array </returns>
public static byte[] Compressbyte (byte[] data)
24 {
MemoryStream ms = new MemoryStream ();
-Stream s=new Gzipoutputstream (MS);
S.write (data, 0, data.) Length);
S.close ();
Return Ms. ToArray ();
30}
31
/**////<summary>
33///Decompression Data
///</summary>
///<param name= "Data" > byte array to extract </param>
///<returns> extracted byte array </returns>
Notoginseng public static byte[] Decompressbyte (byte[] data)
38 {
byte[] WriteData = new byte[2048];
MemoryStream ms= new MemoryStream (data);
The stream sm = new Gzipinputstream (ms) as Stream;
MemoryStream outstream = new MemoryStream ();
while (true)
44 {
size int = Sm. Read (writedata,0, writedata.length);
if (size >0)
47 {
Outstream.write (writedata,0,size);
49}
Or else
51 {
The break;
53}
54}
Sm. Close ();
byte[] Outarr = Outstream.toarray ();
Outstream.close ();
Outarr return;
59}
60}
61}

And then we're in the page control class that derives from the LoadPageStateFromPersistenceMedium () and Savepagestatetopersistencemedium (Object viewState ), the code is as follows:

1Load & Save ViewState data#region Load & Save ViewState Data
2 protected Override Object LoadPageStateFromPersistenceMedium ()
3 {
4//read data from the hidden domain __smartviewstate that you registered
5 string viewState = request.form["__smartviewstate"];
6 byte[] bytes = convert.frombase64string (viewState);
7//Call the static method provided above Compressionhelper.decompressbyte () to extract the data
8 bytes = compressionhelper.decompressbyte (bytes);
9 LosFormatter formatter = new LosFormatter ();
Ten return formatter. Deserialize (convert.tobase64string (bytes));
11
12}
13
protected override void Savepagestatetopersistencemedium (Object viewState)
15 {
LosFormatter formatter = new LosFormatter ();
StringWriter writer = new StringWriter ();
Formatter. Serialize (writer, viewState);
String viewstatestring = writer. ToString ();
byte[] bytes = convert.frombase64string (viewstatestring);
21//Call the static method provided above Compressionhelper.compressbyte () to compress the data
bytes = compressionhelper.compressbyte (bytes);
23
24//Register a new hidden domain __smartviewstate, you can also define your own
this. RegisterHiddenField ("__smartviewstate", convert.tobase64string (bytes));
26}
27#endregion

Through the above processing, the source code in the Web output page is the type such as:

<input type= "hidden" name= __smartviewstate "value=" h4siaptponwa/81ce1pbwjb/...
<input type= "hidden" name= "__viewstate" value= ""/>

The original hidden field "__viewstate" value is empty, and replaced by our own registration of the new hidden domain "__smartviewstate" to store the compressed string, so the speed effect is obvious, combined with our project, Like Dg3g.com home the original ViewState string value is about 28K, compressed to 7 K, and acafa.com the original ViewState string value is about 43K, compressed after 8K. This kind of processing is still more satisfactory. Of course, if you think it's not thorough enough, you can also store the ViewState string in session, but in this way, the pressure on the server memory will be steep (especially when the traffic is larger), it is recommended or not easy to use, if you have a Web server memory 10G, 8G, you may wish to try. The following are the relevant code for modification:

The code in the LoadPageStateFromPersistenceMedium () method Body of the above:
String viewState = request.form["__smartviewstate"];
Modified to:
String viewState = session["__smartviewstate"]. ToString ();
Also, the code in the above Savepagestatetopersistencemedium () body is:
This. RegisterHiddenField ("__smartviewstate", convert.tobase64string (bytes));
Modified to:
session["__smartviewstate"] = convert.tobase64string (bytes);

Finally, the above code and program are from VS2003 development practice, the VS2005 is suitable, I do not make any commitment, but if you can get from the above program, I will be extremely happy.



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.