David Basarab
David Basarab

Reputation: 73301

ASP.NET removing an item from Session?

Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

Upvotes: 57

Views: 64798

Answers (5)

Buu
Buu

Reputation: 50335

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.

Upvotes: 124

splattne
splattne

Reputation: 104030

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.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."

Upvotes: 11

JakubRi
JakubRi

Reputation: 849

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();

Upvotes: 27

FlySwat
FlySwat

Reputation: 175573

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.

Upvotes: 4

dove
dove

Reputation: 20674

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.

Upvotes: 10

Related Questions