Reputation: 3098
When I need to save a big list of my Custom Objects between postbacks on my Asp.Net project, I like to save them in a Session Variable, then Cast them to a List<> in a property Something like this
public partial class MyPage : Page
{
private List<MyStorageObject> MyList
{
get {return (List<MyStorageObject>) Session["MySessionString"]; }
set { Session["MySessionString"] = value; }
}
}
Then I put a List of my objects in there, and get to call it in a later postback. I think this is a pretty standard way to make objects last longer than the page LifeCycle.
But my question is, when I'm using the List more than once, say I'm going to do a few things with it, I can't help but think every time I access it, it's casting an object to a List<> but if I create a variable it looks like it's avoiding the casting.
private void DoStuffWithMyList()
{
var x = MyList;
//Assuming I'm going to call the list 20 times in my method
x.first(); // Is this any more efficient / cleaner
MyList.first(); // Than this?
//Or do they both get converted into the same thing in the end anyway
}
Upvotes: 0
Views: 88
Reputation: 6249
Of course avoiding the casting is more efficient.
Why not combine the two?:
private List<MyStorageObject> _MyList = null;
private List<MyStorageObject> MyList
{
get {
if (this._MyList == null)
{
this._MyList = (List<MyStorageObject>)Session["MySessionString"];
}
return this._MyList;
}
set {
this._MyList = value;
Session["MySessionString"] = value;
}
}
Upvotes: 1
Reputation: 1502336
Yes, in the first case (using x
) you're only accessing the property once and then reusing the returned value.
In the second case (using MyList
multiple times) you'll be looking the value up in the session every time you use it. It's also casting, but that's likely to be cheaper than the session lookup.
Fundamentally I'd regard the first version as cleaner, as it makes it clearer that you're trying to reuse the same value several times.
Upvotes: 2