3

I was wondering how wasteful is calling Session object like these (example):

string test = string.Empty;
for (int i = 0; i < 1000; i++)
{
   test += Session["test"].ToString() + ",";
}

Instead of like these:

string test = string.Empty;
string test_session_value = Session["test"].ToString();
for (int i = 0; i < 1000; i++)
{
   test += test_session_value + ",";
}

(that is calling HttpSessionState object and reading session from it multiple times rather than just as fewer times as possible)

Is there any performance penalty (noticeable)? How much should developer be careful with HttpSessionState object usage?

Janez
  • 2,336
  • 5
  • 25
  • 37

2 Answers2

4

The session is fully reader when the page load, and saved when the page unloaded. So the serialize and un-serialize are happens only one time per page !

Session saved/keep the data in a Dictionary<string,object> object.

So when you made this

string test = string.Empty;
for (int i = 0; i < 1000; i++)
{
   test += Session["test"].ToString() + ",";
}

you actually the Session is call the Dictionary that is very fast when locate an item on his list because is use indexing.

Now what I have to notice in this code is that you make a mistake using the string that is the real costly line. To make real fast you must use StringBuilder, but let say that is not a real code but just the way you show it.

StringBuilder test = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
   test.Append(Session["test"].ToString());
   test.Append(',');
}

Is there any performance penalty ?

In real life I do not think that you call 1000 times per page a session variable, so it will no noticeable delay from Session. What is noticeable is that the session is lock all users until the page load and unload.

Relative: Replacing ASP.Net's session entirely

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150
1

If Session state is stored in IIS then it will create bulky the IIS.

If session state is stored in Sql server then transfer of data between different application domain will be time costly.

Advantages: 1. You can access the same session state across machines.
2. Same session state is available after reloading the app_pool.

Disadvantages: 1. Slower than in process mode.
2. All objects in the session state have to be serializable.
3. Since Session variables can be created on the fly, used whenever, and do not require the developer to dispose of them explicitly, the overuse of Session variables can lead to very unreadable and unmaintainable code.

Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92