jack jack - 3 months ago 7x
PHP Question

cache large data in session on memcache server

I had set two memcached server for my php server to cache some database data in session.

When I select more than 20000 records with 20 columns data and cache into php session, it would take more than 1 second to do session_start();

Why? And how can I speed up it?


I think it takes a long time to start a session because memcache and PHP have to unserialize hundreds of thousands of table cells for every request. I bet it takes longer than if you just used a database.

Your implementation is really inefficient: if a single user needs access to her session, you load data about all users. To speed things up significantly, change how you store values in the cache; store only the current user's data, not the whole table!

Instead of building the cache this way:

$SESSION['data'] = [
    'ID_1'=>['name'=>'jane', 'email'=>'...'],
    'ID_2'=>['name'=>'john', 'email'=>'...'],
    ... //20,000 rows

Just do this:

$SESSION['data'] = [
    'ID_1'=>['name'=>'jane', 'email'=>'...']//a single row

Now when you call session_start() only the current users' row is loaded, not the whole table.


My response was addressing an individual user browsing his pages. In the case of an admin who requires the script to filter through all records, I would just access the database with SELECT statements. Make sure to select only the columns and the rows needed. It will probably be faster than loading the whole table from the cache.

Anyway, you can test it very quickly by commenting out session_start() and all $_SESSION references, and querying the database for the info you need.