PHP String Concatenation, Performance

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.

Performance overhead for PHP string concatenation?

Yes, this will increase performance. sprintf is an additonal function call, your string must be scanned for the %s which requires additional time.

The second option using the string concat operator (.) is faster, but the third alternative, just placing the string variable in a string is fastest due to other optimizations that PHP performs.

Anyway, while investigating how PHP deals with string concatination and how it performs is interesting you should never create sql queries like this, because it opens your code to SQL injections. apply mysql_real_escape() to your parameters first or use prepared statements.

PHP: Performance difference between string concat and buffering contents

Here's a benchmark for you:

<?php

$test_1_start = microtime();

$str = '';
for ( $x = 0; $x <= 10000; $x++ ) {
$str .= 'I am string ' . $x . "\n";
}

$test_1_end = microtime();
unset($str);
echo 'String concatenation: ' . ( $test_1_end - $test_1_start ) . ' seconds';

$test_2_start = microtime();

ob_start();
for ( $x = 0; $x <= 10000; $x++ ) {
echo 'I am string ', $x, "\n";
}
$str = ob_get_contents();
ob_end_clean();

$test_2_end = microtime();

echo "\nOutput buffering: " . ( $test_2_end - $test_2_start ) . ' seconds';

?>

My results:

$ php -v
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ php test.php
String concatenation: 0.003932 seconds
Output buffering: 0.002841 seconds%
$ php test.php
String concatenation: 0.004179 seconds
Output buffering: 0.002796 seconds%
$ php test.php
String concatenation: 0.006768 seconds
Output buffering: 0.002849 seconds%
$ php test.php
String concatenation: 0.004925 seconds
Output buffering: 0.002764 seconds%
$ php test.php
String concatenation: 0.004066 seconds
Output buffering: 0.002792 seconds%
$ php test.php
String concatenation: 0.004049 seconds
Output buffering: 0.002837 seconds%

Looks like output buffering + echo is consistently faster, at least in the CLI / on my machine.

Brendan Long made a good point in his comment, however — there is such a minor performance difference here that a choice of one or the other is not much of an issue.

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.

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

PHP String concatenation - $a $b vs $a . . $b - performance

Depending on the PHP version, it varies by how much the second is faster if you write it like:
$newstring = $a . ' and ' . $b . ' went out to see ' . $c;

PHP is very inconsistent from version to version and build to build when it comes to performance, you have to test it for yourself.
What nees to be said is that it also depends on the type of $a, $b and $c, as you can see below.

When you use ", PHP parses the string to see if there are any variable/placeholders used inside of it, but if you use only ' PHP treats it as a simple string without any further processing. So generally ' should be faster. At least in theory. In practice you must test.


Results(in seconds):

a, b, c are integers:
all inside " : 1.2370789051056
split up using " : 1.2362520694733
split up using ' : 1.2344131469727

a, b, c are strings:
all inside " : 0.67671513557434
split up using " : 0.7719099521637
split up using ' : 0.78600907325745 <--- this is always the slowest in the group. PHP, 'nough said

Using this code with Zend Server CE PHP 5.3:

<?php

echo 'a, b, c are integers:<br />';
$a = $b = $c = 123;

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = "$a and $b went out to see $c";
$t = xdebug_time_index() - $t;
echo 'all inside " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = $a . " and " . $b . " went out to see " . $c;
$t = xdebug_time_index() - $t;
echo 'split up using " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = $a . ' and ' . $b . ' went out to see ' . $c;
$t = xdebug_time_index() - $t;
echo 'split up using \' : ', $t, '<br /><br />a, b, c are strings:<br />';

$a = $b = $c = '123';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = "$a and $b went out to see $c";
$t = xdebug_time_index() - $t;
echo 'all inside " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = $a . " and " . $b . " went out to see " . $c;
$t = xdebug_time_index() - $t;
echo 'split up using " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
$newstring = $a . ' and ' . $b . ' went out to see ' . $c;
$t = xdebug_time_index() - $t;
echo 'split up using \' : ', $t, '<br />';

?>

PHP HTML generation - using string concatention

It's a bit old, but this post by Sara Golemon will probably help. AFAIK the output buffering functions are quite fast and efficient and so is echo, so that's what I would use.

What's the fastest way of concatenating strings in PHP?

Code sample 1 won't work at all..

Syntax considerations set aside, Sample 1 should be trivially faster because it doesn't involve parsing a string (looking for variables).

But it's very, very trivial..



Related Topics



Leave a reply



Submit