tags:

views:

195

answers:

6
+1  Q: 

PHP "" vs ''

Hello, I'm just wondering what's more costly, something like:

echo "Hello world, my name is $name";

or

echo 'Hello world, my name is '.$name;

I know in this case it wouldn't make much difference, but maybe here it would:

for($i = 0; $i < 10000; $i++)
{
    echo 'Hello world, my name is '.$name;
}

Thanks in advance!

A: 

Why don't you time it to see?

sybreon
I don't have access to my test server right now
Carlo
All you need is the PHP executable, not the test-server.
sybreon
Or xampp (http://www.apachefriends.org/en/xampp.html) or equivalent
Shabbyrobe
A: 

According to PHP's docs:

Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

That means using single quotes in your loop would probably be faster.

Colin Burnett
+16  A: 

Personally, I would use:

echo 'Hello ' , $name;

echo takes multiple arguments, so there is no need to concatenate for something like this. Here is a benchmark that shows the difference between ' and " (virtually none). However, " allows for escape sequences (\n, etc), and variable expansion.

This type of thing is a micro-optimization and you shouldn't worry about it. See the following threads about optimization:

http://stackoverflow.com/questions/710263/how-important-is-optimization http://stackoverflow.com/questions/127765/php-optimization-tips http://stackoverflow.com/questions/416914/optimizing-php-string-concatenation

Nick Presta
+1... this is what I use, and good links!
alex
Here is an older post that backs up your benchmark: http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html
too much php
Thanks for the link, Peter!
Nick Presta
A: 

Running 1000000 iterations takes 0.671s for the first case and 0.494s for the second case on my computer.

So, '' is faster than "".

I am on PHP 5.2.4-2ubuntu5.6 on a pentium 4 2.4GHz

zak23
A: 

See the "string output" section of The PHP Benchmark...

Or just write a few crappy microtime loops and test them for yourself.

ob_start();
$s = microtime(true);
for ($i=0; $i<10000; $i++)
    echo 'Hello world, my name is '.$i."\n";
$end = microtime(true) - $s;
ob_end_clean();
echo $end;
Shabbyrobe
A: 

In addition to the greater efficiency of using the single quotes and concatenation, I prefer that style because my editor's syntax highlighting simply works better. It is made perfectly clear which part of the line is a string literal and which part is a variable.

You can see this in Stack Overflow's syntax highlighting as well.

Travis Beale