Friday 4 September 2009

Short rant about quotes

It seems to me that a high percentage of PHP programmers are making a simple mistake in their code that increases the execution time of their scripts. I certainly seem to be frequently fixing the problem in other people's code, whether I am maintaining a website, or using an open source class or plugin, etc.

To some, the following two statements might appear to be functionally identical, but in the second statement PHP has to parse the double-quoted content and check for any variables to evaluate before outputting it.

<?php

echo 'Hello World, so long and thanks for all the ghoti!';
echo "Hello World, so long and thanks for all the ghoti!";

?>


If you're thinking, "So what? It's just one line..." then you are not thinking like a programmer. "Expect the unexpected" is one of the first rules of defensive programming. Imagine using this statement in a function or method that is executed many times in one script, or if it's called a few hundred times from within a loop, and maybe on a page which suddenly gets ten times the traffic you expected. All those extra CPU cycles quickly start to add up.

Now, think about all the times that static text is used inside your scripts outside of echo statements, because they will be parsed in exactly the same way. It's easy to imagine how this can start making a difference to the resources your site uses.

In a nutshell, if you're not evaluating anything in the string, use single quotes.

NB: ghoti = fish.

1 comment:

  1. I had to come back and post this here as I've just found the following line while porting somebody else's old code:

    echo "<table cellpadding=\"2\" cellspacing=\"1\" border=\"0\">";

    ReplyDelete