PHP Tip, echoing text

When echoing text or assigning variables, your script will execute faster if you use single quotes (apostrophes) instead of quotation marks around text which does not contain variables. For example, consider the following two statements:

echo ‘Hello, world, this is a test!’;

echo “Hello, world, this is a test!”;

Execution of the first statement will be faster than that of the second. When PHP sees a literal string surrounded by quotation marks (double quotes), it takes time to interpret the string and determine whether or not it must be expanded by replacing variable names with their contents. PHP does not perform this step when it encounters a literal string expressed within single quotes. Accordingly, strings surrounded with single quotes will not be expanded. In the following example,

$var = ‘good day’;

echo ‘Today is a $var!’;

…The result would be “Today is a $var,” as PHP would not replace the $var with “good day” in the single-quoted string.

Of course, the speed difference is negotiable; we’re talking milliseconds or even picoseconds worth of execution time for either statement on a fast server. However, the speed improvement in large scripts, e.g. those which contain several hundred or several thousand assignment or echo statements, can be noticeable.

Comments are closed.