My site's menu tree is three layers deep, relatively static, and completely database driven.
I made the presumption that querying the mysql database for the complete menu tree with every page load would be more resource intensive than querying it once and storing it in a $_SESSION variable. My menus take up 77,835 bytes - using strlen(serialize($menuarray))
.
It finally occurred to me that I have no data to back up this presumption and I can't find this answer anywhere. I presume storing in a $_SESSION var eats memory whereas a mysql query essentially uses the same amount of memory (although I can unset the var after the menu is generated) but also taxes the cpu. Both of course will access the disk.
Cookies are a third option and am willing to hear arguments in their favor as well, although I hold a bias against them.
So, for non-sensitive data, would you go Query, $_SESSION, or Cookies and why?
UPDATE I realized that another options would be to cache the serialized menu query output either to the database or the disk.
Or, even cache the HTML output to a file and include
the menus when needed.
UPDATE 2 Just the fact that this question was put on hold hints at something - perhaps that the use of server resources is a fuzzy area. It's strange trying to optimize without a clearer sense of the impacts of memory, cpu cycles, disk access, db connections, etc.
In the end, caching makes sense and I will go with the accepted answer.
I recommend you get from the database and cache the result. You'll just store the result one time, so it will not consume much memory, and you won't make a db query every time you load the page.
You can do it by simply using OPCache, Memcached, Redis, etc. Or, in another way, simply get the value from db, create a file, save the content, and get the value from the file, removing and adding again in certain time intervals.