Monday, April 23, 2012

Compression of Session State in ASP.NET 4.0


We all know that what is session state in ASP.NET and what is it used for. We also know that Session in ASP.NET can be In Proc and Out Proc
Details of ASP.NET session can be find here.


In case of ASP.NET In Proc mode, session data is stored in memory of worker process of IIS; But in case of Out Proc mode there are two options
  •   State Server
  •  SQL Server
If we use Out Proc mode then large amount of data me need to move to SQL Server or state Server this may be an overhead and performance bottleneck. To improve the performance ASP.NET 4.0 introduces
new configuration called as CompressionEnabled. This property is present in SessionStateSection. You can configure the CompressionEnabled  property as below.

Please see above image here sessionState is set to SQLServer and compressionEnabled is set to true. Default value of compressionEnabled  is false.

When set to true value session data is compressed using GZipStream before storing to SQL Server or State Server and same class is used to expand the session data after fetching It from the SQL Server or State Server.

Example 

Let us write following code in default.aspx of a web application

 


Here Employee class is defined as follows


Few points about the code:

1. Class Employee is marked as serializable which is important. Without declaring it as serializable it cannot be stored in the out proc session.
2. Code in file deafult.aspx generates the large data to be stored in session in for loop and then stores data in session as

                Session["lstEmployee"] = lstEmployee;

This stores data in SQL Server.

Now Let us see length of data stored in cases when compressionEnabled true and when compressionEnabled is false.

Case when compressionEnabled = true in web.config


Case when compressionEnabled = false in web.config


 
From the two images above it can be seen that when compressionEnabled is set to true data stored is less 2609 bytes and in case when it is set to false data stored is large 5314 bytes.

Further Reading
Some good articles about the session
How to configure the SQL Server to save session state.

No comments: