PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?

StackOverflow https://stackoverflow.com/questions/431569

  •  08-07-2019
  •  | 
  •  

Question

Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

Was it helpful?

Solution

There is a small difference if you echo the string.

echo $var1,$var2,$var3 // comma (echo with multiple arguments)

is slightly faster than

echo $var1.$var2.$var3 // dot   (concat and echo)

OTHER TIPS

Both PEZ and Topbit are correct. I just want to point out something I think looks better than has been seen here:

$var  = "line 1 \n";
$var .= "line 2 \n";

versus

$var = "line 1 \n"
     . "line 2 \n";

I much prefer the second one to the first one as visually it is obvious your result is the one string $var. It also prevents stupid bugs like:

$var  = "line 1 \n";
$var .= "line 2 \n";
$vat .= "line 3 \n";
$var .= "line 4 \n";

It doesn't matter for a few, short, strings. Use whatever is clearer to read.

But if you have lots of them (say thousands) not so short ones, you'll probably want to keep them in an array and join them together. (As it happens such code is often as easy to read as concatenating the strings using ".=", so you're not sacrificing clarity on the altar of performance.)

EDIT: I don't think my above thinking is valid. PHP's strings are mutable, right?

Won't make a difference. Both are concatenation, so whatever is easiest to read is what you should use.

If you're after best-performing, try using an array and then implode it when you've finished.

$var = array();
$var[] = "line 1\n";
$var[] = "line 2\n";
$var[] = "line 3";
$var = implode('', $var);

Any way you do it the speed difference will be negligible unless you are working with thousands of big strings.

For anything you're concatenating manually in code, performance probably doesn't matter, so readability is king. For me, this often means using heredoc syntax. I don't like the way it breaks my indentation structure, but it's especially nice when you want line breaks and/or tabs inserted correctly into your strings.

I don't think you'll notice for such a short situation. I typically decide for readability reasons which I'm going to use. I only split on two situations, otherwise on one line:

a) Creating a multi-line response so the code somewhat mimics what the user will see. I've found it makes it easier to catch typos and mistakes this way.

$var  = "line 1 \n";
$var .= "line 2 \n";

b) line length. If the line will overflow my window I'll typically break it up so I don't have to go to the end of the line to read the end. Most languages support a line continuation character so I don't really need to break it physically in the code, but just a habit i have since I do work in some languages that don't have it.

The fastest way to get a large amount of data into a single string, is output buffering to capture echo'd output.

ob_start();
/* many echos. For example, in a loop */
$outString = ob_get_contents(); // get the complete string
ob_end_clean();

In general, it's unlikely to make a significant difference to the speed of your program, so make it look obvious what you are doing, since you have to come back to fix/update it later anyhow. Readability is king.

There is no meaningful difference. It's just a matter of coding preference.

I had a hunch that making an array and then imploding might be the fastest way. I was wrong! However doing a $str = $str + $bla is REALLY slow by order of magnitude! It only matters if your doing a ton of concatenations. Here's my test code:

<?php

function doit($n) {

    $str2concat = 'Esta es una prueba. ¿Cuál manera es más rápida?';

    $str = '';

    // option 1
    $start = microtime(true);

    for( $i=0; $i <= $n; $i++ ) {
        $str .= $str2concat;
    }

    $end = microtime(true);
    echo " Concat: $n Iterations, duration:" . ($end-$start) . "\n";

    // option 2
    $str = '';
    $start = microtime(true);

    for( $i=0; $i <= $n; $i++ ) {
        $str = $str . $str2concat;
    }

    $end = microtime(true);
    echo "Concat2: $n Iterations, duration:" . ($end-$start) . "\n";

    // option 3
    $str = [];
    $start = microtime(true);

    for( $i=0; $i <= $n; $i++ ) {
        $str[] = $str2concat;
    }

    $str = implode( $str );
    $end = microtime(true);
    echo "Implode: $n Iterations, duration:" . ($end-$start) . "\n\n";

}

doit( 5000 );
doit( 10000 );
doit( 100000 );

Here are the results that I got:

 Concat: 5000 Iterations, duration:0.0031819343566895
Concat2: 5000 Iterations, duration:0.41280508041382
Implode: 5000 Iterations, duration:0.0094010829925537

 Concat: 10000 Iterations, duration:0.0071289539337158
Concat2: 10000 Iterations, duration:1.776113986969
Implode: 10000 Iterations, duration:0.013410091400146

 Concat: 100000 Iterations, duration:0.06755805015564
Concat2: 100000 Iterations, duration:264.86760401726
Implode: 100000 Iterations, duration:0.12707781791687
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top