Array, Dictionary or List in a session?
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
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.
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.
精彩评论