开发者

Is it faster to recreate an object or store it in a session variable?

Sorry if this seems obvious to the non-noob. Is it faster to:

  • Recreate an object instance each time someone goes to a page during a session

or

  • Store the object instance in a session variable when it first gets created, then always grab it from there when the page is accessed again

I'm not sure if this will turn out to be a "How long is a piece of string?" sort of question, but if it does, then perhaps you could let me know what factors are involved in ma开发者_JS百科king the decision?


Session data is stored as text, not binary data so somewhere behind the scenes when you toss it into the session the object is recreated anyway. It's probably a little bit slower than initializing it yourself since it has to do some string parsing but I doubt it's much to worry about. In short, it probably doesn't make a difference either way.


It certainly depends on how much logic is done, when the object is created. You should do some benchmarks with both variations.


Without measuring it, i'd say storing and retrieving should most times be faster. For recreating objects you have to call possibly multiple constructors, etc, whereas retrieving shouldn't invoke any function calls.


It obviously depends on what fields you have in object, how many of them and how they are populated. Instantion of an object occurs every time you load a page anyway, so it's the matter of fields and their sources.


Just be wary of trying too hard to optimise this. Bear in mind that storing items in session can be heavy, particularly if your site is high traffic.

Also, I've seen a lot of people create an object, which accesses a database and loads it's attributes. This then gets stored in session, updated on postback and then saved back to teh database.

This is fine, but it makes for difficult concurrency checking - say your object has a timestamp of the last time saved - if you reload it each time prior to saving, you can easily check if the timestamp has changed since the last load, in which case you may need to stop the save from going ahead.

Either way, the difference is not going to be huge.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜