With regards to the advice given in the new PHP speed tips article

2,121 views
Skip to first unread message

Gwynne Raskind

unread,
Jun 24, 2009, 12:00:42 PM6/24/09
to Make the Web Faster
With regards to the new article posted at <http://code.google.com/
speed/articles/optimizing-php.html>, all of the advice in it is
completely incorrect. We at the PHP team would like to offer some
thoughts aimed at debunking these claims, which the author has clearly
not verified.

1) "Don't copy variables for no reason".

The Zend Engine at the core of PHP 4 and 5 uses a technique known as
"copy-on-write" memory management. This means that no matter how many
times you assign the value of a variable to another variable, the data
is not copied until you change it. The example the author gives
results in absolutely no significant use of extra memory, as shown in
the following example:

<?php
$data = str_repeat("*", 512 * 1024); // synthesize 512K of data
$memory_used_before = memory_get_usage();
$more_data = $data;
$memory_used_after = memory_get_usage();
print "Before: {$memory_used_before}\nAfter: {$memory_used_after}\n";
?>

PHP 5.3 with thread-safety and debugging compiled in:
Before: 853968
After: 854236

PHP 5.2 without thread-safety or debugging:
Before: 581912
After: 581976

A difference of 268 bytes in debugging mode, or 64 bytes in normal
mode (which most people use). Hardly the MB of memory the article
talks about.

It should also be noted that a PHP script should NEVER echo or store
the raw contents of any user-supplied variable without filtering it
appropriately.

2) "Use single-quotes for strings."

Benchmarks run against PHP 5.2 and 5.3 show that parsing double-quoted
strings with interpolation is no slower (and often faster) than single-
quoted strings using concatenation. When simple strings with no
variables in them are used, the performance is clearly better with
double-quoted strings due to implementation details in the engine. See
the benchmark posted at <http://pastie.org/523023>.

3) "Use echo to print."

Depending on the way PHP is set up on your host, echo can be slower
than print in some cases. Given the example shown, they have equal
performance.

4) "Don't use concatenation with echo."

This is exactly the opposite of correct advice. The engine handles
multiple arguments to echo() in such a way that concatenation (or
double-quoted string interpolation) is actually much faster. See the
benchmark posted at <http://pastie.org/523020>.

5) "Use switch/case instead of if/else."

Finally, this piece of advice is total nonsense. The decision about
when to use switch/case or if/else is purely a matter of coding style;
their speeds are generally more or less equal except in certain
special cases.


Most of these points may have been true in ancient versions (PHP 3, or
very early versions of PHP 4), but they are definitely untrue in
modern PHP. The PHP team urges the author of the article to check his
facts more carefully, and to investigate where his claims of extra
speed are truly coming from (as certain coding patterns, combined with
specific PHP settings, can sometimes make some of the above points
partially true).

We also urge the author to consider the troubling security
implications of his examples, at least one of which suggests an
extremely dangerous coding style.

In the words of Alexander Songe, if you're really concerned about the
speed of your PHP scripts, look into APC (Alternative PHP Cache,
<http://www.php.net/manual/en/book.apc.php>) , "which benchmarks show
increases speed 3-5 times over no opcode optimization".

Please feel free to e-mail me at <gwy...@php.net> (since Google Groups
seems to only want to allow me to use my Gmail address to be in the
group) with questions. You can also join the php-general mailing list
at <http://www.php.net/mailing-lists.php>, or speak to us on the EFNet
IRC channel #php.

Gwynne Raskind

unread,
Jun 24, 2009, 12:54:53 PM6/24/09
to make-the-...@googlegroups.com
I would like to apologize in advance to anyone who finds that this
message may have been posted to the group more than once. Google
Groups seems to be somewhat reluctant to accepting my posting.


With regards to the new article posted at <http://code.google.com/speed/articles/optimizing-php.html
>, all of the advice in it is completely incorrect. We at the PHP
team would like to offer some thoughts aimed at debunking these

claims, claims which the author has clearly not verified.

group) with questions. You can also join the php-internals mailing

list at <http://www.php.net/mailing-lists.php>, or speak to us on the

EFNet IRC channel #php.pecl.

drantin

unread,
Jun 24, 2009, 1:06:26 PM6/24/09
to Make the Web Faster
On Jun 24, 11:54 am, Gwynne Raskind <gwy...@darkrainfall.org> wrote:
> I would like to apologize in advance to anyone who finds that this  
> message may have been posted to the group more than once. Google  
> Groups seems to be somewhat reluctant to accepting my posting.

This group is moderated, any posts (by new members?) have to be
approved by whomever is doing the moderation before they appear. This
requires moderator intervention so the time until your post appears
can vary from post to post.

GreenReaper

unread,
Jun 24, 2009, 1:26:21 PM6/24/09
to Make the Web Faster
> > I would like to apologize in advance to anyone who finds that this  
> > message may have been posted to the group more than once. Google  
> > Groups seems to be somewhat reluctant to accepting my posting.
>
> This group is moderated, any posts (by new members?) have to be
> approved by whomever is doing the moderation before they appear. This
> requires moderator intervention so the time until your post appears
> can vary from post to post.

Another suggestion to Google, then - an indication of moderation would
be appropriate. When I posted my message, I seem to recall that it
would appear "momentarily". Waiting for moderation is not
"momentarily" in my book. :-)

Johannes Manhave

unread,
Jun 24, 2009, 1:53:00 PM6/24/09
to make-the-...@googlegroups.com

Alex Songe

unread,
Jun 24, 2009, 1:58:31 PM6/24/09
to Make the Web Faster
Some valid beginner optimizations that save much more on performance:

Include and require statements:

Good: include("./foo.php"); // looks for the file in the current
working directory
Bad: include("foo.php"); // searches every directory in include_path
for foo.php, leads to many more disk hits and is hard to cache

It's best to not rely on include_path at all. But when you stop
relying on "." (the current working directory) being in "include_path"
and if you must rely on include_path, you can remove yet another
directory in the include_path list. Setting include_path to use as
few directories as possible. Also be sure to put the most used
directory first.

Using include_once and require_once is also much slower than
structuring your code to include needed files only once (you do not
have to consult the list of loaded files). Includes that rely on both
include_once AND include_path to load the file have their load times
compounded by these mistakes.

Any opcode cache will singlehandedly bring a huge optimization to a
php installation. APC, EAccelerator, and Xcache are 3 popular opcode
cachers.

Code with as few warnings and notices as possible! Each time the
warning/notice logger is called, it will slow down script execution
noticeably. Common mistakes are array keys: $foo['bar'] works much
better than $foo[bar]. Use isset() or empty() instead of @ to hide
errors like undefined variables or array indices. They are also
faster than array_key_exists. Using the @ operator to silence errors
is also a huge speed decrease, as php has to change error_reporting
back after the end of the statement.

Turn on output_buffering! Php can chunk output for you to deliver
code faster. Just turn it on. Turn of implicit flush as well. It's
better to let entire chunks of php get sent out until the end of the
request, when a flush is done there too.

Turn off register_globals, magic_quotes_gpc (specifically if your code
is secure), register_argc_argv, always_populate_raw_post_data,
session.use_trans_sid, session.auto_start.

Use built-in constants before functions (PHP_VERSION vs php_version(),
PHP_OS vs php_uname('s'), etc).

Good resources (written by the guys who actually work on the php
engine):

http://ilia.ws/files/phptek2007_performance.pdf
http://ilia.ws/files/phpquebec_2009.pdf

Christos Apartoglou (Χρήστος Απαρτόγλου)

unread,
Jun 24, 2009, 2:41:06 PM6/24/09
to make-the-...@googlegroups.com
Hi GreenReaper

Good catch - a note about this group being moderated is now in the group welcome message.

Thanks!

erich...@gmail.com

unread,
Jun 24, 2009, 6:20:04 PM6/24/09
to Make the Web Faster
Hi Gwynne, thank you for your feedback!

A point that I'd like to make, which I hope to include in the article
as well, is that the sites which suffer from slow performance often
aren't those running the latest version of the PHP engine, but rather
older versions such as 4 and even 3. Many times, and in my own
experience, large amounts of this legacy will exist in a company's
codebase, and updating it to be fully compatible and tested with a
newer version of the PHP engine isn't a viable option. The purpose of
the tips we're offering in this article is to provide some quick and
easy changes that might help to improve the performance of their code,
without a lot of development overhead.

I do agree that we could do a better job of pointing out the version
differences in the article, and I'm happy to make those notes and
changes soon.

Additionally, I think that some of our PHP code samples may have been
a bit oversimplified to the point that they are causing some of the
confusion and concerns being discussed here. I'll be sure to update
those as well.

I hope that your team of developers would be open to contributing to
our selection of articles, so that we all can work together to make
the web faster!

Thanks,
Eric

erich...@gmail.com

unread,
Jun 24, 2009, 6:20:59 PM6/24/09
to Make the Web Faster
Hi Gwynne, thank you for your feedback!

A point that I'd like to make, which I hope to include in the article
as well, is that the sites which suffer from slow performance often
aren't those running the latest version of the PHP engine, but rather
older versions such as 4 and even 3. Many times, and in my own
experience, large amounts of this legacy will exist in a company's
codebase, and updating it to be fully compatible and tested with a
newer version of the PHP engine isn't a viable option. The purpose of
the tips we're offering in this article is to provide some quick and
easy changes that might help to improve the performance of their code,
without a lot of development overhead.

I do agree that we could do a better job of pointing out the version
differences in the article, and I'm happy to make those notes and
changes soon.

Additionally, I think that some of our PHP code samples may have been
a bit oversimplified to the point that they are causing some of the
confusion and concerns being discussed here. I'll be sure to update
those as well.

I hope that your team of developers would be open to contributing to
our selection of articles, so that we all can work together to make
the web faster!

Thanks,
Eric

On Jun 24, 9:54 am, Gwynne Raskind <gwy...@darkrainfall.org> wrote:

Joeri Sebrechts

unread,
Jun 26, 2009, 3:43:28 AM6/26/09
to Make the Web Faster
You talk about "older versions such as 4 and even 3". Who is running
versions of PHP that are that old on the open internet? If you're
running on PHP3 or PHP4 on a public-facing website, your very first
priority is to upgrade to PHP5 for security reasons, not to optimize
your pages.

As a full-time PHP programmer, I would have to agree that the micro-
optimization suggestions mentioned in the PHP recommendations article
probably won't impact an average PHP application much, if at all.
Where I've run into performance bottlenecks, they've been mostly
related to:
(1) superfluous or inefficient database queries
(2) bad algorithm design (e.g. loops within loops within loops, when a
single loop would do)
(3) many small writes to the page, instead of using buffered output
(4) doing stuff in PHP code that PHP has native functions for (e.g.
json encoding/decoding, or char-by-char string parsing instead of
regex-based parsing)
What I've found is that performance-wise it's better to favor clean
code than micro-optimized code, even in PHP. That means you DO in fact
copy variables if it makes your algorithm cleaner.

So, in recommending improvements to the article, I would say the
priorities should be:
1. Upgrading PHP
2. Reducing database queries, and optimizing existing queries. Using
memcache to cache database results.
3. Using an opcode cache
4. Using buffered output
5. Using built-in functions where possible
6. Using a caching template engine
7. Using xdebug profiling and kcachegrind to analyze for specific
bottlenecks in the code (this is the only way to really _know_ where
the bottlenecks are in PHP code).

I would remove the following recommendations, because they don't apply
to (what I consider) the most commonly used PHP versions out there:
1. Using single quotes
2. Don't copy variables
3. Use switch instead of if

If I can be of any help in improving this article, just say the word.

On Jun 25, 12:20 am, "erichigg...@google.com" <erichigg...@gmail.com>
wrote:

itpastorn

unread,
Jun 26, 2009, 5:35:40 AM6/26/09
to Make the Web Faster
Also for speed reasons one should upgrade to PHP 5:
http://sebastian-bergmann.de/archives/858-Flickr-The-Real-World-PHP-5-Benchmark.html

If upgrading is not an option, make it an option! That is simply the
only good advice on can give people still on PHP 3 or 4.

Refactoring the code to PHP 5 is a much better way of spending
programming hours than rewriting code to run faster in old setups.

On Jun 25, 12:20 am, "erichigg...@google.com" <erichigg...@gmail.com>
wrote:

Justin Johnson

unread,
Jun 27, 2009, 1:22:39 AM6/27/09
to Make the Web Faster
> Turn on output_buffering!  Php can chunk output for you to deliver
> code faster.  Just turn it on. Turn of implicit flush as well.  It's
> better to let entire chunks of php get sent out until the end of the
> request, when a flush is done there too.

Output buffering does not necessarily deliver output faster. In fact,
this block from php.ini (5.2.9) states that it can even make it
slower:

; Output buffering allows you to send header lines (including cookies)
even
; after you send body content, at the price of slowing PHP's output
layer a
; bit. You can enable output buffering during runtime by calling the
output
; buffering functions. You can also enable output buffering for all
files by
; setting this directive to On. If you wish to limit the size of the
buffer
; to a certain size - you can use a maximum number of bytes instead of
'On', as
; a value for this directive (e.g., output_buffering=4096).

In fact, in some cases it is better not to buffer and instead flush()
as earlier and as often as possible.

Justin Johnson

unread,
Jun 27, 2009, 1:35:22 AM6/27/09
to Make the Web Faster
> You talk about "older versions such as 4 and even 3". Who is running
> versions of PHP that are that old on the open internet? If you're
> running on PHP3 or PHP4 on a public-facing website, your very first
> priority is to upgrade to PHP5 for security reasons, not to optimize
> your pages.

It's not always an option to upgrade to the latest version of PHP for
some corporations. My last place of employment was an all PHP shop
that has been around for about 10 years now. When I first started
there, they were just migrating to PHP 5 (not even the latest version
of 5) and were facing all sorts of problems with legacy code. Besides
their custom compiled modules (in c) that broke and were heavily
relied on by the rest of the site, one specific case that I recall was
the difference in how objects are copied in PHP 4 vs 5. We all spent
many hours inserting `clone` statements throughout the site.

Refactoring required most-to-all of the dev team (who were already
over-allocated), and wasn't good business sense as far as the
stakeholders were concerned. Needless to say it took months but is
finally ... 5.2.1 :(

Gwynne Raskind

unread,
Jun 27, 2009, 7:53:31 AM6/27/09
to make-the-...@googlegroups.com


We knew the changes in OOP for PHP 5 would cause problems for people,
but we went ahead with them anyway, because, quite simply, it needed
to be done.

As for using an older version of 5.2, we do our very best *not* to
break backwards compatibility between point releases. If it works in
5.2.1, then it'll work in 5.2.10, unless you were relying on buggy
behavior that we fixed. Yes, regressions do sometimes slip past us,
but in the general case, updating from point release to point release
is usually painless and transparent. We're always fixing security
holes, speed issues, and broken behaviors, so you should carefully
consider what's holding you back from taking advantage of these updates.

-- Gwynne

Gwynne Raskind

unread,
Jun 27, 2009, 7:53:31 AM6/27/09
to make-the-...@googlegroups.com
On Jun 27, 2009, at 1:35 AM, Justin Johnson wrote:

rawseo

unread,
Jun 27, 2009, 12:37:09 PM6/27/09
to Make the Web Faster
I have also written an article that can also help out with php
application performance:

http://www.rawseo.com/news/2009/06/25/better-ways-to-improve-php-application-performance/

Adam Piper

unread,
Jun 28, 2009, 6:03:01 AM6/28/09
to Make the Web Faster
> 2) "Use single-quotes for strings."
>
> Benchmarks run against PHP 5.2 and 5.3 show that parsing double-quoted
> strings with interpolation is no slower (and often faster) than single-
> quoted strings using concatenation. When simple strings with no
> variables in them are used, the performance is clearly better with
> double-quoted strings due to implementation details in the engine. See
> the benchmark posted at <http://pastie.org/523023>.

Both your evidence and my own testing with PHP 5.2.9 suggest the
opposite from your statement.

i.e. Your evidence supports the position of Eric Higgins.

Please amend your statement or explain yourself further.

Alex Songe

unread,
Jun 29, 2009, 10:06:16 AM6/29/09
to Make the Web Faster
Nothing is wrong with the statement, you're just not interpreting it
very accurately...the difference is very small and slightly in the
favor of single quotes whenever a handful of variables are used.
However, when no variables are used, double quotes may be faster
because of implementation details in the engine.

These micro-optimizations can't get you more than 1 or 2 extra
requests per second done on a box...if that request has several tens
of thousands of variable interpolation operations. This is a LOT of
work for no real reward. Caching solutions and configuration tweaks
yield much higher results.

The point is that these recommendations in the best case scenario
won't yield the phenomenal jump in time per request that some of the
recommendations on this list have (opcode optimizations, configuration
changes, writing proper loops, avoiding nested loops, caching
configuration to memory, etc). I have personal experience in bringing
a php webservice from 20rps to 500rps...and I'm sure many other people
have...these tips would've gotten me from 20rps to 22rps...the
optimizations in the article just aren't worth it.

Kenneth Ismert

unread,
Jul 13, 2009, 12:16:24 PM7/13/09
to Make the Web Faster
Eric,

I've came across this topic on PHP Architect. At first, this sounded
like yet another pointless religious debate over old hot-button
topics. So, I decided to research your 'single vs. double qoutes'
performance claim, just to find out what to believe. I reached this
conclusion:

You are an irresponsible journalist.

A big part of writing any article is getting your facts straight.
Here's what I found:

The PHP Benchmark
http://www.phpbench.com/
See 'Quote Types' at the bottom of the page. Common string handling is
about the same for both quote types. In the author's words, 'Lets all
join together in harmony in this one!'

Microbenchmarks of single and double qouting.
http://www.procata.com/blog/archives/2005/03/08/microbenchmarks-of-single-and-double-qouting/
This one in particular speaks to your assertion that long strings
perform better with single quotes. This benchmark shows virtually no
difference in parsing times. If there is no difference in parsing, and
no real difference at runtime, where is your 'poor performance' coming
from?

So, here's where I stand on your article:

You failed utterly to do any research, or produce any benchmark code
to back your claims. You made your readers do your work for you,
wasted a lot of people's time, and spread misinformation, which you
have not corrected at the time of this post.

Please tell me how this article is a service to the web community.

-Ken

On Jun 24, 5:20 pm, "erichigg...@google.com" <erichigg...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages