view state压缩优化提速
2009-04-05 18:19
585 查看
Introduction
Recently, I developed a huge ASP.NET page, with more than 30 controls. As we all know, it's a good idea to disable the ViewState for the controls that don't actually need it, sayLiterals or
Labels. After doing that, I noticed that the hidden ViewState field was still a few KBs big. This is obviously a big problem for the users that still don't have a broadband connection, because uploading 40 KB to the server is really a bad issue, especially when they begin to click the "Submit" button again and again because they don't notice any response. So, after a few searches through the Internet, I built a simple solution to compress the ViewState and therefore save a rough 50% of the bandwidth. This post by Scott Hanselman has been particularly useful. Although it's possible to use external libraries to perform compression tasks, I think the better solution is to use the
GZipStreamor
DeflateStreamthat the .NET Framework 2.0 includes.
Compressing and Decompressing Data in Memory
First of all, we need a way to compress and decompress an array of bytes in memory. I put together this simple static class that exposes two methods:Compressand
Decompress. The two available classes,
GZipStreamand
DeflateStream, according to MSDN, use the same algorithm, so it's irrelevant which one you choose.
The code below is really simple, and doesn't need further explanation:
Collapse
Copy Code
using System.IO; using System.IO.Compression; public static class Compressor { 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 and put it in the App_Code directory of your ASP.NET application, making sure it's contained in the proper custom namespace (if you don't specify any namespace, the class will be available in the built-in ASP namespace).
Compressing the ViewState
Now, we can actually compress the ViewState of the page. To do that, we have to override the two methodsLoadPageStateFromPersistenceMediumand
SavePageStateToPersistenceMedium. The code simply uses an additional hidden field,
__VSTATE, to store the compressed ViewState. As you can see, by viewing the HTML of the page, the
__VIEWSTATEfield is empty, while our
__VSTATEfield contains the compressed ViewState, encoded in Base64. Let's see the code.
Collapse
Copy Code
public partial class MyPage : System.Web.UI.Page { protected override object LoadPageStateFromPersistenceMedium() { string viewState = Request.Form["__VSTATE"]; byte[] bytes = Convert.FromBase64String(viewState); bytes = Compressor.Decompress(bytes); LosFormatter formatter = new LosFormatter(); return formatter.Deserialize(Convert.ToBase64String(bytes)); } protected override void SavePageStateToPersistenceMedium(object viewState) { LosFormatter formatter = new LosFormatter(); StringWriter writer = new StringWriter(); formatter.Serialize(writer, viewState); string viewStateString = writer.ToString(); byte[] bytes = Convert.FromBase64String(viewStateString); bytes = Compressor.Compress(bytes); ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes)); } // The rest of your code here... }
In the first method, we just decode from Base64, decompress and deserialize the content of the
__VSTATE, and return it to the runtime. In the second method, we perform the opposite operation: serialize, compress, and encode in Base64. The Base64 string is then saved into the
__VSTATEhidden field. The
LosFormatterobject performs the serialization and deserialization tasks.
You may also want to create a new class, for example,
CompressedPage, inheriting from
System.Web.UI.Page, in which you override the two methods and then inherit your page from that class, for example
MyPage : CompressedPage. Just remember that .NET has only single inheritance, and by following this way, you "spend" your only inheritance chance to use the ViewState compression. On the other hand, overriding the two methods in every class is a waste of time, so you have to choose the way that best fits your needs.
Performances and Conclusions
After a few tests, I noticed that the ViewState has been reduced from 38 KB to 17 KB, saving 44%. Supposing you have an average of 1 postback per minute per user, you could save more than 885 MB of bandwidth per month on every single user. That's an excellent result: you save bandwidth (and therefore money), and the user notices a shorter server response time.I wanted to point out that this solution has a performance hit on the server's hardware. Compressing, decompressing, encoding, and decoding data is quite a heavy work for the server, so you have to balance the number of users with your CPU power and RAM.
License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.A list of licenses authors might use can be found here
相关文章推荐
- ASP.Net中的ViewState解析和压缩以及页面性能优化
- ASP.Net中的ViewState解析和压缩以及页面性能优化
- 重写PageStatePersister属性 自定义压缩方法来减小ViewState大小来优化页面加载时间
- ViewState优化——压缩技术
- ViewState实现和优化2--自定义压缩方法采用GZipStream压缩
- 网页优化系列三:使用压缩后置viewstate
- [翻译]asp.net 2.0中通过压缩ViewState改善性能
- Asp.Net 性能 ViewState 压缩的2种方法
- asp.net 2.0中通过压缩ViewState改善性能
- ExtAspNet应用技巧(七) - ViewState优化
- WordPress优化:利用Autoptimize插件压缩网页提速
- [翻译]asp.net 2.0中通过压缩ViewState改善性能
- asp.net 中通过压缩ViewState改善性能
- 压缩ASP.NET中的ViewState的改进方法
- 压缩ASP.NET中的ViewState
- ExtAspNet应用技巧(七) - ViewState优化
- 调整ViewState的位置,搜索引擎优化
- [翻译]asp.net 2.0中通过压缩ViewState改善性能
- 压缩ASP.NET中的ViewState的改进方法
- 压缩页面的VIEWSTATE