Log in

No account? Create an account

Concatenation in PHP

« previous entry | next entry »
Feb. 13th, 2008 | 02:39 pm
location: Singapore
mood: contemplativecontemplative
music: Whirring fans, tweeting birds

Something I've sometimes wondered is if there is a difference between these:

$a .= 'a';
$a = $a . 'a';

It turns out that there is. A big difference. A loop doing the first one 100,000 times takes only 0.17 seconds. But the same loop using the second version takes 1.95 seconds. That's quite a difference.

I believe the general rule in PHP is that if you use a neater way of writing the code, you will get more efficient code. PHP doesn't do even simple optimizations like the case above. PHP has left such optimizations to be done by bytecode optimizers, rather than by the core php system. The reason is that these optimizations will take time, and in many cases there is no benefit (such as when code is executed once only). Given that compilation usually takes place on every script run, compilation time is very important.

Such optimizations can be done by APC, the alternative php cacher. This cache will also store compiled versions of scripts.

Link | Leave a comment | Share

Comments {0}