Thursday, March 6, 2008

Single Quotes versus Double Quotes

Any time you put something in "double" quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.

$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }

Those same three lines of code could be executed much faster if 'single' quotes were used in place of "double" quotes.

$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }

Now that may not seem like much, but having PHP check for variables where it doesn't need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within 'single' quotes.

echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:

echo $mytext . 'Lisa needs braces.';

As opposed to this bit of molasses-like code:

echo "$mytext Lisa needs braces.";

No comments: