PHP Variable Interpolation VS Concatenation

Speed difference in using inline strings vs concatenation in php5?

Well, as with all "What might be faster in real life" questions, you can't beat a real life test.

function timeFunc($function, $runs)
{
$times = array();

for ($i = 0; $i < $runs; $i++)
{
$time = microtime();
call_user_func($function);
$times[$i] = microtime() - $time;
}

return array_sum($times) / $runs;
}

function Method1()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are $foo";
}

function Method2()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are {$foo}";
}

function Method3()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are " . $foo;
}

print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";

Give it a few runs to page everything in, then...

0.0035568

0.0035388

0.0025394

So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, after all the work to parse out the variable and trim/copy up the original string.

Updates By Somnath:

I added Method4() to above real time logic.

function Method4()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = 'these are ' . $foo;
}

print timeFunc('Method4', 10) . "\n";

Results were:

0.0014739
0.0015574
0.0011955
0.001169

When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point.

Which is more efficient: string concatenation or substitution?

I got curious, so... Though OP: You can figure this out with the right question.

<?php

$a = 'YES';

$start_time = microtime(TRUE);
$test = "Yow $a";
echo $test . "\n";
$end_time = microtime(TRUE);
echo $end_time - $start_time;

echo "\n\n";

$start_time = microtime(TRUE);
$test = 'Yow ' . $a;
echo $test . "\n";
$end_time = microtime(TRUE);
echo $end_time - $start_time;

echo "\n\n";

Outputs:

1st run:

Yow YES
4.1007995605469E-5

Yow YES
6.9141387939453E-6

2nd run:

Yow YES
4.3869018554688E-5

Yow YES
8.8214874267578E-6

So using single quote then concatenate is better.

Variable string concatenation and interpolation, string is stored in array

You are using single quotes, so no string interpolation is done, if you want strings interpolated you have to use double quotes"$var":

$arr = array( 1,2,3);
$i = 0;

echo '$arr[0]'; // prints: $arr[0] <== Your error is here
echo "$arr[0]"; // prints: 1

A better approach

Anyways, you may like to do it this way:

$array = array(12, 34);    
$s = implode("', '", $array); // $s is: 12', '34
$s = ", '$s'"; // $s is: '12', '34'

echo $s; // prints: , '12', '34'

Performance of variable expansion vs. sprintf in PHP

In all cases the second won't be faster, since you are supplying a double-quoted string, which have to be parsed for variables as well. If you are going for micro-optimization, the proper way is:

$message = sprintf('The request %s has %d errors', $request, $n);

Still, I believe the seconds is slower (as @Pekka pointed the difference actually do not matter), because of the overhead of a function call, parsing string, converting values, etc. But please, note, the 2 lines of code are not equivalent, since in the second case $n is converted to integer. if $n is "no error" then the first line will output:

The request $request has no error errors

While the second one will output:

The request $request has 0 errors

Should I use curly brackets or concatenate variables within strings?

All of the following does the same if you look at the output.

  1. $greeting = "Welcome, " . $name . "!";
  2. $greeting = 'Welcome, ' . $name . '!';
  3. $greeting = "Welcome, $name!";
  4. $greeting = "Welcome, {$name}!";

You should not be using option 1, use option 2 instead. Both option 3 and 4 are the same. For a simple variable, braces are optional. But if you are using array elements, you must use braces; e.g.: $greeting = "Welcome, {$user['name']}!";. Therefore as a standard, braces are used if variable interpolation is used, instead of concatenation.

But if characters such as tab (\t), new-line (\n) are used, they must be within double quotations.

Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate. Therefore decide depending on how many variables among other characters.

PHP - concatenate or directly insert variables in string

Between those two syntaxes, you should really choose the one you prefer :-)

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

The result will be the same; and even if there are performance implications, those won't matter 1.


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.

That day, you'll need to use {}:

echo "Welcome {$name}s!"

No need to fallback to concatenations.


Also note that your first syntax:

echo "Welcome ".$name."!";

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(But, as I said earlier, this doesn't matter much...)


1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

String concatenation in PHP (with a variable inside of it) , which one has a better performance?

Let's make some new test, is really simple

Live example

Test

<?
$str1 = $str2 = "";

for ($i=0; $i < 10000; $i++) {
$start = microtime(true);
$str1 .= 'You got ' . $i . ' messages';
$str1_test[] = microtime(true) - $start;
}

echo "Dotted: " . ($str1_result = array_sum($str1_test) / 10000);

echo PHP_EOL;

for ($i=0; $i < 10000; $i++) {
$start = microtime(true);
$str2 .= "You got {$i} messages";
$str2_test[] = microtime(true) - $start;
}

echo "Interpolated: " . ($str2_result = array_sum($str2_test) / 10000);
echo PHP_EOL . ($str2_result < $str1_result ? "Interpolation" : "Dot") . " is faster!";

Result

Dotted: 1.1234998703003E-6
Interpolated: 1.2600898742676E-6
Dot is faster!

Real fact

The difference is to small to be significative, I personally like the interpolation, is elegant and faster to read, is up to you! ;)



Related Topics



Leave a reply



Submit