I have a web page where users can log in and then in various sections the page shows some data about the user - like email address, phone number, name, last name, etc (about 30 values in total). In your opinion, what's better - saving the data into session variable that is accessible the whole session every time i need something or making a db request every time i need some of those values? Performance wise mostly.


Recommended Answers

All 6 Replies

It's probably simpler to get them from the DB. Otherwise, each time you want to access a value, you need to check if the session variables have been loaded and if not go to the module / function that loads them. There are purists who always look for the most efficient way to do things even if it makes little real-world difference. I don't belong to that group. If you have that much traffic or you will be doing this often enough that it will make any real performance difference, then do the session variable version. Otherwise, just read them when you need them.

Thanks for the reply. Currently i'm storing them in session variables. They are all loaded only once - on login, or if the user changes some information, like name, etc. I was just wondering if too many or too large session variables can slow down the performance too much. The site is expected to have pretty high amount of traffic, so i'd want to be careful with request amount on page load.

Member Avatar

I've hit this problem too. I was told by a few experts that using a DB is better as it's quicker than using sessions (which involves file operations).
Consequently I am now going to just pass the bare minimum via session (e.g. user id) and then retrieve info from db.

Also, what if the session is stored in a database table? Would that make much difference?

Member Avatar

No difference AFAIK

I would store just an id in the session.

Storing info in a session causes some problems, especially when debugging. For example you store the users information in a session, but they update it. Now you have to modify the session and the database.

This next example comes from a problem I experienced when trying to update a coworkers code. He decided to store the user group (admin/super admin/etc) data in a session. I needed to change between different user groups for testing purposes, so I went to the database and updated the user group. Since the session wasn't updated, the user never changed groups and I had to logout and clear my session cookies every freaking time. Just annoying.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.