PHP M

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Optimizing PHP

WHAT’S IN THIS CHAPTER?

• Using opcode caching to speed up execution

• Handling PHP sessions

• Profiling bottlenecks with xhprof

• Optimizing your PHP code


• This chapter starts with a look at PHP modules and extensions.
• How too many extensions can adversely affect performance.
• As well as situations in which it can be worth writing your own.
• After that, we learn about opcode caching, a powerful technique that can
overcome many of the limitations of an interpreted language
• We also learn about why Alternative PHP Cache (APC) is rapidly becoming
the standard in this field.
• Sessions are widely used in PHP, but introduce their own performance
considerations — particularly in load-balanced environments.
• where a means to share session data across back-end servers is sometimes
needed.
• you discover various solutions to these problems, including the use of
Memcache to store session data.
EXTENSIONS AND COMPILING
• Removing Unneeded Extensions:
• The PHP source code comes bundled with more than 80 extensions
that provide additional functionality, ranging from image
manipulation to XML parsing to database interaction.
• When compiling PHP, you have the option of building extensions
statically into the PHP binary, or as shared modules that can be
loaded at run time.
• The one disadvantage to compiling in extensions is that there is a little
extra overhead involved in dynamically loading shared extensions.
• Following table shows the size of some of the most common modules
in a PHP version 5.3 installation.
• Common libraries such as libcrypto and libssl will almost
certainly already be in memory, whereas more esoteric ones
such as libXdmcp.so (which provides interaction with the X
Display Manager and is linked into gd.so on Linux) probably
won’t be.

• All this means that determining the memory footprint of a


particular PHP extension is no simple matter. Actually, it’s
somewhat ambiguous as to how you even define the memory
footprint.
Writing Your Own PHP Extensions:
• PHP extensions have all the usual benefits of being written in a
compiled language (C) — they are faster to execute and have a lower
memory footprint, and there is a much lower delay before they begin
executing.
• That’s why extra features like GD or MySQL support are built as
extensions rather than PHP libraries.
• Custom PHP extensions are by no means pointless, but they are
definitely something to consider only after you have exhausted the
possibilities described so far.
Compiling:
• Aside from giving you complete control over installed modules, compiling
PHP from the source also enables you to implement the usual compile-
time performance options.
• For example, with GCC under Linux, the -O3 switch is commonly used to
produce a higher level of optimization.
• A particularly useful configuration flag is --disable-all.
• You can selectively re-enable them later in the list of ./configure options.
• Remember that, for Apache, you must compile --with-apxs
• Following are two particularly useful options:
1. --enable-inline-optimization.
2. --disable-debug
 OPCODE CACHING:
• What are OpCode Caches?
• OpCode Caches are a performance-enhancing extension for
PHP.
• They do this by injecting themselves into the execution life-
cycle of PHP and caching the results of the compilation phase
for later reuse.
• It is not uncommon to see a 3x performance increase just by
enabling an OpCode cache.
• When Should You Use an OpCode Cache?
• Given that OpCode Caches have almost no side-effects beyond
extra memory usage (to store the cache), they should always be
used in production environments.
• Which OpCode Cache?
• Throughout PHPs lifetime there have been a number of
OpCode caches;
• One of the first was from Zend (which has had several
names), however, it was proprietary.
• Therefore, for the last few years the primary cache being
used has been APC — Alternative PHP Cache.
• While APC is great, it lacks some features found in Zend’s
offering and additionally lacked maintainers to bring it up to
speed for the latest PHP versions.
OPCODE CACHING:
• In PHP, execution happens in two steps:

1. The lexical parser compiles the script into opcode (sometimes also
referred to as bytecode).

2. The Zend engine at the heart of PHP executes the opcode.


Variations of Opcode Caches
• For a long time, the big three were XCache (written by the author of
Lighttpd), Turck MMCache, and eAccelerator (itself a fork of
MMCache). eAccelerator has been a personal favorite of the author,
but neither it nor MMCache is maintained any longer.
Getting to Know APC
• Depending on how you install, entries may be added to php.ini to load
and configure APC, or a separate configuration file may be created
(most likely under etcphp5/conf.d/).
• A minimum configuration such as the following would simply load the
APC extension:
extension=apc.so
Memory Management
• The first decision is whether to use shared memory (shm) or mapped
memory (mmap), and likely this decision has already been made for
you.
• There isn’t a huge difference in performance between the two.
• shm is more portable, but mmap is slightly more efficient with
memory management.
Time-To-Live (TTL)
• Like all good caches of finite size, APC utilizes a Time-To-Live (TTL) to set
the maximum lifetime for cache entries.
• This option is controlled by apc.ttl and defaults to zero.
• APC can be configured to also check a file’s ctime, as shown here:
• apc.stat =1 ## standard mtime check apc.stat_ctime = 1 ## also check
ctime
Locking
• APC supports the following four locking methods:
• File locks — These are the most stable but offer poor performance.
• IPC semaphores — These are faster than file locks and well supported.
• Pthread mutex — These are only available in Linux version 2.6 onward
but offer a much greater performance gain.
• Spin locks — These offer the best performance of all but are still
considered experimental.
Sample apc.ini

apc.enabled = 1

apc.stat = 0

apc.stat_ctime = 0

apc.slam_defense = 0

apc.write_lock = 1

apc.ttl = 7200

apc.optimization = 0
APC Caching Strategies
• As shown in Figure, fragmentation occurs when items are removed
from the middle of the cache, leaving a gap that is either not big
enough to hold another item, or that holds an item but leaves a small
gap.
• APC has two settings that provide control over exactly what is cached:
• apc.cache_by_default — This controls whether to cache by default.
• apc.filters — This lets you supply a comma-separated list of regexes to
control what is cached and what isn’t.
• If cached_by_default is set to zero, the regexes in apc.filters can be
prepended with a +, indicating that any file matching the pattern
should be cached.
• Conversely, if cache_by_default is set to one, the regexes can be
prepended with a -, telling APC not to cache any matches.
• So, if you want to cache everything except the contents of the /admin
directory and a particularly large script, you could use the following:

• Or if you want to cache only the contents of a particular directory, you


could use the following:
Monitoring the Cache
• APC comes bundled with a PHP script, apc.php, which provides a web
interface for monitoring and administration of the cache.
• If you have the PHP GD module enabled, you’ll also get some nice pie
charts showing cache usage and the hit-to-miss ratio
Using APC as a Generic Cache
• APC can also be used as a generic in-memory cache, much like Memcache.
• Using APC in this way has the benefit of no latency being incurred when
connecting to Memcache (which may be running on a different machine)
and simplified server administration because there is one less service to
manage.
• The following code writes a variable called foo (with a value of bar) to the
cache and sets the TTL to 1 hour:
• (3,600 seconds): apc_add("foo", "bar", 3600);
• You can later retrieve the value of foo like so:
• $foo = apc_fetch("foo"); print $foo;
Warming the Cache
• If you’re using HAProxy, ramping can be used to gradually bring the server
back into the pool, slowly increasing the weight so that it is not swamped with
connections until the cache has had a chance to warm up.
• Alternatively, APC has a couple of tricks of its own.
• You can use apc_compile_file() to ask APC to parse and compile a file and store
the opcode in the cache.
• Following is an example: apc_bin_dumpfile(null, null,"tmpapcdump.data");
Using APC with FastCGI
• Over the years, PHP has supported several methods of running as a
CGI, including
• fcgi and FastCGI,
• and these methods have not worked well with APC.
COMPILING PHP
• Given that interpreted languages are inherently slower than compiled
ones, the thought of compiling PHP into an executable format is a
tempting one.
• Despite the potential gains, PHP compilation isn’t an area that has
gained widespread interest.
• Over the years, there have been numerous attempts to create a PHP
compiler, and although some have been reasonably successful, none
have gone on to widespread usage.
COMPILING PHP
• Phc
• Phalanger
• HipHop
SESSIONS

• Storing Sessions
• Storing Sessions in memcache/membase
• Using Shared Memory or tmpfs
• Session AutoStart
• Sessions and Caching
• Following table shows four possible values for session.cache_limiter, along with the HTTP
headers that they cause to be send.

You might also like