Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Session - big object vs many small objects

I have a scenario to optimise how my web app is storing data in the session and retrieving it. I should point out that I'm using SQL Server as my session store.

My scenario is I need to store a list of unique IDs mapped to string values in the user's session for later use. The current code I've inherited is using a List<T> with a custom object but I can already see some kind of dictionary is far better for performance.

I've tested two ideas for alternatives:

  1. Storing a Dictionary<int, string> in the session. When I need to get the strings back, I get the dictionary from the session once and can test each ID on the dictionary object.

  2. Since the session is basically like a dictionary itself, store the string directly in the session using a unique session key e.g. Session["MyString_<id>"] = stringValue". Getting the value out of the session would basically be the inverse operation.

My test results show the following based on the operation I need to do and using 100 strings:

  • Dictionary - 4552 bytes, 0.1071 seconds to do operation
  • Session Direct - 4441 bytes, 0.0845 seconds to do operation

From these results I see that I save some space in the session (probably because I've not got the overhead of serialising a dictionary object) and it seems to be faster when getting the values back from the session, maybe because strings are faster to deserialise than objects.

So my question is, is it better for performance to store lots of smaller objects in session rather than one big one? Is there some disadvantage for storing lots of smaller objects vs. one bigger object that I haven't seen?

like image 293
Peter Monks Avatar asked Feb 24 '12 10:02

Peter Monks


1 Answers

There are penalties for serializing and searching large objects (they take up more space and processor time due to the need to represent a more complex structure).

And why do 2 searches when you can do only one.

Also, all documentation that deal with caching/storing solutions mention that it is much more efficient to serialize a single value from a list based on a computed key, rather than store all the dictionary and retrieve that and search in it.

like image 131
linkerro Avatar answered Oct 17 '22 17:10

linkerro