2
votes

Scott Hanselman recently posted a blog article describing how to compress strings stored in the session / cache. This looks fairly promising, but the majority of data that I am storing in the session / cache are not strings but custom classes. How would you go about compressing these?

My initial thought would be to utilize the BinaryFormatter to serialize the object first (just like the ASP.NET framework would do normally when storing custom class objects into the session / cache), then compress the resulting byte array. However, this has the adverse side effect that the retrieved data from the session / cache would be readonly (since decompressing and deserializing would create a new in-memory object).

In other words, if my code currently looks like the following, is there a way to compress its storage into the session?

MyClass foo = new MyClass();
Session["foo"] = foo;

MyClass retrievedFoo1 = (MyClass) Session["foo"];
retrievedFoo1.Property1 = "property 1";

// retrievedFoo2.Property1 should equal "property 1"!
MyClass retrievedFoo2 = (MyClass) Session["foo"];
3
Objects stored in Session are only serialized with the Binary serializer if they are stored out-of-process (e.g. stored in SQL Server).Jason Bunting
Ok, so how do you compress that data before storing it into SQL server?Kevin Pang
If you're storing the data in SQL server why would you really then need to compress it?jmcd

3 Answers

1
votes

Firstly I'd look at why you need to compress the data in your session / cache. Compression should be an act of last resort, better programming should be the first.

Are you running out of memory, and if so, which objects are consuming the most? This should point you in the direction for code improvement to reduce the amount of memory used.

If your app is optimised the best it can with the objects it needs, you may want to look at out of memory storage such as a database or file system to cache larger objects (which is where serialisation comes in handy).

You could also place InProc sessions on a different server to the webserver to improve scalability and distribute the site over a web farm.

0
votes

Could you use an XML Serializer to transformed it into an XML format?

0
votes

It is my understanding that the performance degradation you get from (overloading) the Session is due to the overhead of serialization/deserialization, not storage size. If you are looking at compression to help with performance issues I think you're going down the wrong road. (De)Compression will just add more overhead.

Now if you're talking about the Cache, then things are a bit different. But you specifically mention Session...


I'm confused by your question having just read your comment on Scott's article. It seems you don't really understand you're getting data persistence by putting something in Session/Cache the same as if you put it into a database or wrote it to file. Compression isn't going to solve what you're asking about.