Tuesday, March 23, 2010

APC - Alternative PHP Cache

I am working on a heavy traffic social networking site (build in php), we are already using Memcache and some other file based caching techniques. Our team decided to use any opcode cahing which can cache compiled code, we decided to use APC.

APC (Alternative PHP Cache)

We all know that php is an interpreted Language, when we request for any page, following process happens -
1. Load the script.
2. Parse the script.
3. Compile into opcode.
4. Execute the script.
When we use any opcode caching(here is APC), it cache the compile code in memory. So when this page will again accessed it reads the compile code from memory and execute it. This process saves the step #1,#2,#3. So it saves time and computer resources both.

Installing APC - APC is free open source package by PECL,. It is actively maintained and most probably will be include in php6. Here are the easy steps to install it -
1. Download the package from http://pecl.php.net/package/APC
2. Untar it
$ tar -xzvf APC-3.1.3p1.tgz
3. Go in APC folder
$ APC-3.1.3p1
4. $ phpize
5. $ ./configure --enable-apc --enable-apc-mmap --with-apxs --with-php-config=/usr/local/bin/php-config (check your php config path it may be /usr/bin/php-config also)
6.$ make
7.$ make test
8.$ make install
9 Insert following entry in your php.ini
extension=apc.so
6. Move apc.so in your php modules folder
$ mv /usr/local/lib/php/extensions/no-debug-non-zts-20060613/apc.so /usr/lib/php/modules/
7. Now restart your apache.

Once the APC has installed you can configure it. APC has vast range of run time configuration option( lke setting segments, segments size, file ttl, user ttl etc). You can find full list here - http://in3.php.net/manual/en/apc.configuration.php
With the use of APC_UPLOAD_PROGRESS you can create progress meter also.

After configuration move apc.php in your root directory. Now run apc.php, it will show you all the valuable information, Even it shows the memory usage and fragmentation graph, all the files and user variable cached etc.


I have not use eAccelerator but i read at several places that in performance eAccelerator is little better than APC, but eAccelerator is not stable. eAccelerator produce regular fatal errors, needing to restart Apache. Please read these links -
http://drupal.org/node/323736
http://www.simplemachines.org/community/index.php?topic=364083.0

Since APC is stable, actively maintained, undergoing with quick development and most probably will include in php 6 so, i recommend APC. But definately i'll test eAccelerator and Xcache also to compare the result with APC.