Cache data in PHP SESSION, or query from db each time?

后端 未结 2 976
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 06:34

Is it \"better\" (more efficient, faster, more secure, etc) to (A) cache data that is used on every page load in the $_SESSION array (but still querying a table for a flag t

2条回答
  •  星月不相逢
    2021-01-12 07:27

    If your data is used on every pages, and is the same for all users, I wouldn't cache it in $_SESSION (which means having a different copy of that data for each user), but with another mecanism, like :

    • file
    • In memory, with APC for instance (if only 1 server)
    • In memory, with memcached, for instance (if you have several servers)
    • If your data requires long calculations or several DB queries to be obtained, caching it in database could be another possibility (would mean only 1 query to fetch back, and less calculations)


    If your data is not the same for each user (which seems to be the case in your situation, as you are caching names, birthdates, ...) :

    • I would make sure I only cache what is necessary
    • Once you only have a few data to cache, putting it in session should be quite OK
    • If you really have that many users, you'll probably have some other scalability problems, and will most likely come to use something like memcached anyway ; which means you'll have some other way of caching ;-)

    As a sidenote : if you are doing the same query over and over again, you DB server should cache it by itself (for MySQL, it would go into the "query cache") ; so, it would not be as bad as you think, I suppose -- even if not that much optimized ^^

提交回复
热议问题