Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   Save in _SESSION vs re-do db lookup (http://www.go4expert.com/forums/save-session-vs-db-lookup-t29898/)

David Ledger 10Nov2013 23:02

Save in _SESSION vs re-do db lookup
Sometimes a PHP script needs to load a lot of data from a db and do some processing on it before use by the main chunk of the script, and that same script is used to process the submission of a form created by the first invocation of the script. I can see two ways of making that processed data generated during the first invocation available to the second. The normal way is simply to re-do the db lookups and the processing each time the script is invoked. The second way is to save the data in _SESSION so that later invocations just *have* the data pulled in by the system. (If the user has cookies disabled it has to revert to the re-lookup of course).

I have used both methods but I'm wondering if anyone has ever done any real server load testing to compare the two methods. The second method is subjectively as fast, but I'm not able to compare the two.



shabbir 11Nov2013 10:11

Re: Save in _SESSION vs re-do db lookup

You are spot on that second method is fast but then when compared to first method you have to understand the table scan. If you have lot of rows in the table where you have the date stored then it makes much more sense to be storing the data in session variable.

Also session and cookie is different and I don't recommend using cookies but session variables that are stored in the server and not on user browser.

Also if you want you can serialize the data and store them in a separate table as well.

I hope it helps.


David Ledger 11Nov2013 15:41

Re: Save in _SESSION vs re-do db lookup
Thanks Shabbir.

I realise that the session data isn't stored in cookies, but the session id that allows the server to recover $_SESSION for that id is. You always have to do "if data not already in $_SESSION then load it into there" and then use it from $_SESSION.

I hadn't thought of putting the serialised data into the db rather than using the built-in session data saving. I wonder which is quicker / lower server load. You would have to manage the serialised data for old sessions though.



shabbir 11Nov2013 18:04

Re: Save in _SESSION vs re-do db lookup
Serialized data can save big table scans but then if table data updates, then serialized data needs to be updated as well. Update / Delete operation on Data should invalidate the serialized data or update the serialized data.

Also one more option to look at is Database Object Caching using XCache or APC and that can help you save lot of table scans.

All times are GMT +5.5. The time now is 08:54.