Last night I spent some time trying to improve the speed of my project management system and PHP in general. My first move was to turn on profiling in PHP’s xdebug extension to determine what was taking the time. One obvious candidate for improvement was session_start() which was taking about 20% of the time.
Improving session_start() performance is not so obvious as introducing caching on a frequently-used database call. First I tried introducing more agressive garbage collection for stale material – This increased performance in some cases, but still not to a point that I wanted to stop. By default, PHP sessions are stored as files on disk, with all their associated overhead and latency. For performance, it would be better to keep sessions (especially frequently used ones, like those used by my AJAX framework) in memory where they can be accessed with only minimal delay.
Rather wonderfully, there’s a PHP extension in PECL that adds memcached support to PHP (memcached is, as the name suggests, a memory caching server). In addition to allowing object-oriented access to memcached within PHP scripts, it adds a new session save handler that stores sessions in memcached rather than on disk. (OpenSuSE has a package for in, in the PHP Extensions repository.)
Once memcache and the PHP extension are installed, it’s just a case of altering the session save handler in php.ini:
session.save_handler = memcache
session.save_path = “tcp://127.0.0.1:11211”
I also installed a PHP memcached monitor script, phpMemcachedAdmin, which displays detailed memcached usage information.