Compressing ASP.NET 2.0 Viewstate
One thing I was looking forward with asp.net 2.0 release was improved viewstate optimization. The truth is it has improved, but for me there is still something desirable to be had.
Where I have run into the problems is a web application I am working on the must allow the user to add an infinate amount of web controls dynamically. The results below are pretty amazing. I ended up using SharpZipLib for the compressing algorithm.
Test Scenerio: One web page with that ended up with 116 asp.net web controls add to it.
Result of ViewState Size:
Before Compression: 43.3 KB
After Compression using SharpZipLib: 3.50 KB
Below is the code to get you started
Imports System.IO
Imports Zip = ICSharpCode.SharpZipLib.Zip.Compression
Public Class PageViewStateZip : Inherits System.Web.UI.Page
Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
Dim vState As String = Me.Request.Form(“__VSTATE”)
Dim bytes As Byte() = System.Convert.FromBase64String(vState)
bytes = vioZip.Decompress(bytes)
Dim format As New LosFormatter
Return format.Deserialize(System.Convert.ToBase64String(bytes))
End Function
Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
Dim format As New LosFormatter
Dim writer As New StringWriter
format.Serialize(writer, viewState)
Dim viewStateStr As String = writer.ToString()
Dim bytes As Byte() = System.Convert.FromBase64String(viewStateStr)
bytes = vioZip.Compress(bytes)
Dim vStateStr As String = System.Convert.ToBase64String(bytes)
RegisterHiddenField(“__VSTATE”, vStateStr)
End Sub
End Class
Public Class vioZip
Shared Function Compress(ByVal bytes() As Byte) As Byte()
Dim memory As New MemoryStream
Dim stream = New Zip.Streams.DeflaterOutputStream(memory, _
New Zip.Deflater(Zip.Deflater.BEST_COMPRESSION), 131072)
stream.Write(bytes, 0, bytes.Length)
stream.Close()
Return memory.ToArray()
End Function
Shared Function Decompress(ByVal bytes() As Byte) As Byte()
Dim stream = New Zip.Streams.InflaterInputStream(New MemoryStream(bytes))
Dim memory As New MemoryStream
Dim writeData(4096) As Byte
Dim size As Integer
While True
size = stream.Read(writeData, 0, writeData.Length)
If size > 0 Then memory.Write(writeData, 0, size) Else Exit While
End While
stream.Close()
Return memory.ToArray()
End Function
End Class
Written by Tim on March 2nd, 2006 with 32 comments.
Read more articles on asp.net.
