ASP.NET removing an item from Session?

Is there a difference?

There is. Session.Remove(key) deletes the entry (both key & value) from the dictionary while Session[key] = null assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the Session#Keys collection. But after the latter, the key can still be found in the key collection.


I know this is old thread but definitely stick with Session["key"] = null - it's much more faster! I've done some tests (on InProc Session State), removing 1000 items in row (elapsed time is for 1000 items totally, so if you want average time for one item, just divide it with 1000):

Removing 1000 existing items:

Session[key] = null; - 0.82380000000000009 ms
Session.Remove(key); - 59.960100000000004 ms

Removing 1000 NOT existing items:

Session[key] = null; - 1.5368000000000002 ms
Session.Remove(key); - 0.6621 ms

Removing 500 existing and 500 not existing items:

Session[key] = null; - 1.0432000000000001 ms
Session.Remove(key); - 33.9502 ms

Here is a piece of code for first test:

Session.Clear();

for (int i = 0; i < 1000; i++)
    Session[i.ToString()] = new object();

Stopwatch sw1 = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
    Session[i.ToString()] = null;
sw1.Stop();

Session.Clear();

for (int i = 0; i < 1000; i++)
    Session[i.ToString()] = new object();

Stopwatch sw2 = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
    Session.Remove(i.ToString());
sw2.Stop();

It has the same effect. I personally think that the Session.Remove method does express the programmer's intent better.

Here some links to the documentation on MSDN:

  • HttpSessionState Class
  • HttpSessionState.Item Property (String)

"HttpSessionState.Item Property:

Property Value Type: System.Object

The session-state value with the specified name, or null reference (Nothing in Visual Basic) if the item does not exist."


I would go with Remove but can not honestly say if there is a difference. At a guess there may still be an empty key kept for that null value but not sure. Remove would give me little doubt and if that's what you want to do it reads better in code as well.


The biggest difference is how you read from session.

if(Session.ContainsKey["foo"]) { return Session["foo"]; }

or

if(Session["foo"] != null) { return Session["foo"]; }

If you use the first method, setting the value to null will not work, and you should use remove.

If you use the second method, you can set the value to null.