Is a variable stored in a session deserialized one or more times during the page life cycle?

I would like to bind session variables in the same way as discussed in CodeProject .

public static class WebSession { private const string CurrentUserKey = "CurrentUser"; private static HttpSessionState Session { get { return HttpContext.Current.Session; } } public static bool Exists { get { return Session != null; } } public static User CurrentUser { get { return Session[CurrentUserKey] as User; } set { Session[CurrentUserKey] = value; } } } 

Here is my question: if I need to access CurrentUser several times on the same page, would I get a performance boost by assigning it to a local variable instead of accessing the wrapping property? Or is HttpSessionState executed so that the object is only deserialized once per request, so that subsequent calls in the same HTTP request are no longer worth it?

Thanks Aaron

+6
c # session-variables
source share
4 answers

Each request has a copy of the session state in memory. Therefore, the only price you would save by copying a session variable is that you selected an object from your object. Then a copy in memory is added to the session at the end of the request.

Regardless of whether the session is serialized and deserialized on the page, it depends on which session provider you choose. Serialization fails for In-proc session state. For session servers, the object must first be serialized.

+6
source share

There is a copy in mind. You get a slight performance improvement from caching values; he would save only a search in the Dictionary, which would be too fast to notice if you do not do it a million times to load the page.

It is also important to note that for a given key, each retrieval returns a link to the same instance, and Session also saves the link. This means that if you retrieve an object from a session and modify it, you do not need to call the setter again to re-serialize it.

I just asked a question about this: Are .NET setters ever called implicitly?

+4
source share

I digressed several times from the session, and from what I could see, the entire state object was deserialized once and only once per request. Of course, just checking is enough - just pull it out twice and check ReferenceEquals .

Of course, placing the value in the field between uses will save some search time, but you only have to pay the cost of deserialization.

If you really want to be sure, you can also double check this by doing ISerializable and running serialize / deserialize calls.

+3
source share

All Articles