views:

183

answers:

2

Hey,

What would be the most efficient way of storing a set of values in a session? I'm guessing it's either a List/Array or Dictionary. Basically, when a user selects an item from a DropDownList, a value (between 1 and N where N <= 20) is sent back to the server. I'd then like this value to be used as an index (if using arrays) or key (if using a dictionary) within the session. I don't want the value to be seen by the user, hence why it's not stored in the DDL. From what I gather, dictionaries are designed for key-lookups. However, since the scale is quite small, are there any overheads of using a dictionary that could make it less efficient in this case? Each corresponding value is unique to the user, so I've decided to use sessions.

Thanks for any advice

A: 

Almost certainly a micro-optimization, but the absolute highest performance will most likely come from arrays. Your best bet is to try all your options and validate empirically.

BioBuckyBall
+2  A: 

Arrays would be best option for you here.

Dictionary could be more scalable if you are intending to add some more custom type with minimal changes in code. Fetching an item from Dictionary is usually a 1 hop operation. But the only overhead involved in using Dictionary is serialization. Serialization will only be involved when you use SQLServer or StateServer to store your sessions.

I did some benchmarking where I used BinaryFormatter to serialize an array of int, List, and a Dictionary.

I serialized each object 100000 time. Each data-structure contains 20 values. Here are the results:

int[] took 1955 ms to serialize
List<int> took 4135 ms to serialize
Dictionary<int,int> took 27917ms to serialize

So be careful when using Dictionary when serialization is involved.

======================================== To support my argument that fetching an item from dictionary is quiet efficient, I also did some benchmarking where I stored 20 items in each data-structure (which I used above) and fetched items for 10000000 times. Here are the results

int[] took 136 ms to serialize
List<int> took 184 ms to serialize
Dictionary<int,int> took 877 ms to serialize

Sure a little slower then the other two, but it provides more scalability then the other two data-structure.

But if it is a fixed number of items, then go for Arrays. They are the most efficient in this case.

cornerback84
Thanks for the reply! Are there any threading issues I should be worried about?
Skoder
You would be using session, so you don't have to worry about threads. Sessions providers take care of locking.But if you are using any global or static variables, then you have to be careful.
cornerback84
No global variables, and the only static variable is my logging class. Thanks for the help.
Skoder