Friday, September 4, 2009

PHP speed up: Quote your strings

I've wanted to post this earlier, but i've been busy lately. So yeah, here's a tip off on how to speed things up for new or beginner php developers.

You might have noticed, PHP error level by default is set to E_ALL & ~E_NOTICE, which means all errors except notices are reported.

Take a look at the following snippet:
<?php

$test = cool;
echo $test;

?>


You might have noticed that it works fine. The output is still "cool".

But when you set the error level to E_ALL, you get to see an additional line like this one:
Notice: Use of undefined constant cool - assumed 'cool' in /public_html/quotestring.php on line 3

This means what when the line "$test = cool;" is parsed, PHP actually look up whether a constant "cool" exists. If not, it will assume that it is the string "cool". This means that extra time is taken to find the constant.

We ran a test to compare between quotes and no-quotes for a string, and also compared between double quotes and single quotes. the result was amazing (the output on browser):

Notice: Use of undefined constant cool - assumed 'cool' in /public_html/quotestring.php on line 4
cool
0.000458002090454 s
cool
9.05990600586E-6 s
cool
8.10623168945E-6 s

The first one is without quotes (look up constants then decide that it is a string). The 2nd one is using double quotes (look if there are variables or control characters to parse then output) and the last one is using single quotes (just output).

The full PHP code for the test results can be found on Pastebin at the following link:
http://thephpcode.pastebin.com/f7bb6a1f9

So remember to quote your strings with single quotes and occasionally use double quotes to speed things up. I am Sam Yong, signing off.

1 comment:

Dan Dascalescu said...

Just wanted to add that it's a syntax error to quote array keys if the array element is interpolated in a string - see this gotcha from Perl vs. PHP.