Speed Difference in Using Inline Strings VS Concatenation in PHP5

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.

php String Concatenation, Performance

No, there is no type of stringbuilder class in PHP, since strings are mutable.

That being said, there are different ways of building a string, depending on what you're doing.

echo, for example, will accept comma-separated tokens for output.

// This...
echo 'one', 'two';

// Is the same as this
echo 'one';
echo 'two';

What this means is that you can output a complex string without actually using concatenation, which would be slower

// This...
echo 'one', 'two';

// Is faster than this...
echo 'one' . 'two';

If you need to capture this output in a variable, you can do that with the output buffering functions.

Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()

$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );

Lastly, make sure you familiarize yourself with PHP's string type and it's different delimiters, and the implications of each.

Which is faster - $a.$b or $a$b

I would say option A

For basically the same reason you stated

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! ;)

Performance: or ' PHP

You shouldn't even care about this. It makes no real difference. No practical impact.

http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html

https://speakerdeck.com/dshafik/phpaustralia-2015-php-under-the-hood


Lets use the same benchmark data from the post by Mark Smit:

For a real speed benchmarks between quotes you can look at http://www.phpbench.com/

Q: Is a there a difference in using double (") and single (') quotes for strings. Call 1'000x

A: In today's versions of PHP it looks like this argument has been satisfied on both sides of the line. Lets all join together in harmony in this one!

PHP Performance Between Call a Variable VS Direct Value

Option 3 - Don't use single quotes in HTML and simply break out of PHP to do your HTML. If you need to insert variables then do so. You should also NOT be using <tables> for page layout instead use <divs> with CSS.

It will make it much easier to read then concatenating a bunch of HTML with your PHP variables as strings, you also maintain HTML formatting, and it does not affect performance enough that you could possibly notice it.

?>
<div class="fom">
<div class="xbo">
<label class="ftd">Name</label>
<input size="30" maxlength="30" name="name" value="<?= (!empty($_POST['name']) ? htmlentities($_POST['name']) : '') ?>">
</div>
</div>
<div class="fom">
<div class="xbo">
<label class="ftd">Company</label>
<input size="30" maxlength="30" name="company" value="<?= (!empty($_POST['company']) ? htmlentities($_POST['company']) : '') ?>">
</div>
</div>
<div class="fom">
<div class="xbo">
<label class="ftd">Contact</label>
<input size="30" maxlength="12" name="contact" value="<?= (!empty($_POST['contact']) ? htmlentities($_POST['contact']) : '') ?>">
</div>
</div>
<?php

You can even abstract further out and separate your HTML from your PHP logic by using views.

You would have a simple function which loads your HTML which you pass your PHP variables to, it then returns the rendered version for storing into a variable (partial) or echoing out.

function view($view = '', $data = array()) {

if (file_exists($view) === false) {
return 'Partial view not Found';
}

if (!empty($data)) {
extract($data);
}

ob_start();
require($view);
return ob_get_clean();
}

You can then use it like:

echo view('./views/homepage.php', ['result' => $result]);

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.

Is there any reason for not using string interpolation in PHP?

No, there is no reason not to be using string interpolation in PHP.

While there are tiny differences in how PHP handles string interpolation and concatenation internally, those differences are so small that they are barely measurable in practice, and should therefore be left to PHP to handle.

If or when you see benchmarks, for working with strings in PHP, the thing to look for is usually the iteration count. In order to get measurable results you need to set n to some highly exaggerated value, which never occurs in the real world.

To wrap up, optimizing how you work with strings in PHP does not make much sense. Instead, you should focus on problems that actually have a noticeable effect on the performance of your website; caching, database stuff and, especially, the front end.



Related Topics



Leave a reply



Submit