Web design and development for companies and individuals in the Czech Republic
+420 608 713 199

String variables concatenation vs variable interpolation

If you use PHP to write web applications, then you definitely know about different types of putting variables into a string. Here they are:

$var1 = "Some string $var2";

and

$var1 = 'Some string ' . $var2;

What method do you use? Why? Actually long time ago people tested which of the ways was faster. And they came to the conclusion that the second way is much faster. But it was at the time of PHP4. How do you think is it still true for PHP5 or not? Let’s check it:

class Timer {
    private $starttime;
    private $lasttime;

    public function __construct() {
        ;
    }

    public function init() {
        $mtime = $this->getTime();
        $this->starttime = $mtime;
        $this->lasttime = $mtime;
    }

    public function getTime() {
        $mtime = microtime();
        $mtime = explode(" ",$mtime);
        $mtime = $mtime[1] + $mtime[0];
        return $mtime;
    }

    public function getLastTimeDiff() {
        $mtime = $this->getTime();
        $timediff = $mtime - $this->lasttime;
        $this->lasttime = $mtime;
        return $timediff;
    }
}

$timer = new Timer();

$var = 1;
$var = "$var";

for( $x=0; $x < 101; $x++ )
{
    echo "Step: $x\n";

    $timer->init();

    for( $i=0; $i<100001; $i++ )
    {
        $string = " {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var}";
        unset( $string );
    }

    echo "15 embedded vars: ".$timer->getLastTimeDiff()." seconds\n";


    $timer->init();

    for( $i=0; $i<100001; $i++ )
    {
        $string = ' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var;
        unset( $string );
    }

   echo "15 concatenations: ".$timer->getLastTimeDiff()." seconds\n";
}

Using PHP 5.3.8 we got these results:

15 embedded vars: 0.24974799156189 seconds
15 concatenations: 0.40971899032593 seconds

So, putting vars into strings is now almost twice faster than concatenation of them.

P.S. If you comment out $var = "$var";, you will get the script running twice slower, so casting/juggling should be done before such cycles.

Interested in our services?
Hire Us