Benchmarking PHP 5.1.4 string manipulation

Update: see the completely different results for PHP 5.2.3.

On the PHP manual page for the print function, someone's posted a benchmark for various methods of string concatentation/interpolation. The results were really dubious, so I ran a modified version myself (note: may also contain errors, but the results at least seem reasonable). Here's the script, and here are the results:

Php Strings Benchmark (No Interpolation)-1

Php Strings Benchmark (Interpolation)-1


What does this mean?

  1. If there's no interpolation, it doesn't make any difference if you use single or double quotes around strings. However, I'm not entirely sure—in this test—whether PHP is actually parsing the double-quoted string on each iteration: apparently "the first access of microtime() doesn't happen until the php file is completely parsed and converted into opcodes".
  2. If there is interpolation, sprintf is faster than double quotes; I suspect this is because it's easier to search for the locations of %s in a string than to search for $whatever. Neither are as fast as concatenation with single quotes.

Note: these tests were conducted with PHP 5.1.4 on Intel Mac OS 10.4.9.

Note: A first version of these graphs was created in Swivel, but it's so awkward to make graphs and update data I had to get rid of them. Many Eyes is even worse, so I ended up using Google Spreadsheets via Excel. Ugh.