Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a variable stored in Session deserialized once or multiple times throughout a page lifecycle?

I would like to wrap Session variables in a manner similar to that discussed on 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 have to access CurrentUser multiple times in the same page, would I get a performance improvement by assigning it to a local variable instead of accessing the wrapping property? Or does the HttpSessionState make sure the object is only deserialized once per request, so that subsequent calls in the same http request don't cost any more?

Thanks, Aaron

like image 779
devlord Avatar asked Jan 27 '10 20:01

devlord


People also ask

Where Are session variables stored in asp net?

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext. Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.

What are session variables in C#?

Sessions are used to store the data for the user just like cookies. The Session object stores information about, or change settings for a user session. Variables are stored in a Session object hold information about one single user.

What is the purpose of session object?

You can use the Session object to store information needed for a particular user session. Variables stored in the Session object are not discarded when the user jumps between pages in the application; instead, these variables persist for the entire user session.

What is a session object?

The Session object stores information about, or change settings for a user session. Variables stored in a Session object hold information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences.


1 Answers

There is an in-memory copy of your Session state on each request. Therefore the only cost that you would be saving by locally copying a session variable is that of the cast from Object to your type. The in-memory copy is then added to Session at the end of the request.

Whether or not Session is serialized and deserialized on a page depends on what Session Provider you choose. For In-proc Session State, no serialization occurs. For Session Servers the object must be serialized first.

like image 189
Keith Rousseau Avatar answered Oct 13 '22 00:10

Keith Rousseau