Php: output [] w / join vs $ output. =

I am changing the code in which the original author created the web page using an array:

 $output[]=$stuff_from_database;
 $output[]='more stuff';
 // etc
 echo join('',$output);

Can anyone think of a reason why this would be preferable (or vice versa):

 $output =$stuff_from_database;
 $output .='more stuff';
 // etc
 echo $output;
+3
source share
10 answers

It was probably written by someone who came from a language where the strings are unchanged, and therefore, concatenation is expensive. PHP is not one of them, as the following tests show. So the second approach is performance, better. The only reason I can think of using the first approach is the ability to replace part of the array with another, but that means keeping track of indexes that are not specified.

~$ cat join.php
<?php

for ($i=0;$i<50000;$i++) {
$output[] = "HI $i\n";
}

echo join('',$output);
?>


~$ time for i in `seq 100`; do php join.php >> outjoin ; done

real    0m19.145s
user    0m12.045s
sys     0m3.216s

~$ cat dot.php
<?php

for ($i=0;$i<50000;$i++) {
$output.= "HI $i\n";
}

echo $output;
?>


~$ time for i in `seq 100`; do php dot.php >> outdot ; done

real    0m15.530s
user    0m8.985s
sys     0m2.260s
+13
source

This is a little off topic, but

$output =$stuff_from_database;
$output .='more stuff';
// etc
echo $output;

, :

echo = $stuff_from_database;
echo 'more stuff';

, PHP:

ob_start();
echo = $stuff_from_database;
echo 'more stuff';
$output = ob_get_contents();
ob_end_clean();

, , . , , , . , " - ".

+2

, ( ), - , , , join (',', $output ) . (, ",).

, 1000 , , , 10,0000+ .

-, , , , vs cpu, .

+2

< ! - →

, , no-op .

, Contary , ( ) : , , , .

  • UNTRUE. , . (!)
  • UNTRUE: SprintF .

Sprintf ,

PHP 5.2.6-pl7-gentoo (cli) (built: Sep 21 2008 13:43:03) 
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    with Xdebug v2.0.3, Copyright (c) 2002-2007, by Derick Rethans

, .:/

+1

, - . , , , .

echo $stuff_from_database
   , 'more stuff'
   , 'yet more'
   // etc
   , 'last stuff';
+1

$output, , , . . , , , , .

0

implode() join(), PHP . , . ". =" free() malloc() .

0

; - . , ( ) , . , , , . !

0

If you create a list (for example, a shopping cart), you must have a code that generates HTML from each entry retrieved from the database.

for ($prod in $cart)
{
  $prod->printHTML();
}

Or something like that. Thus, the code becomes much cleaner. Of course, this assumes that you have good code with objects, and not some idiotic mess like my company (and replaces).

0
source

That has already been said, but I think a great answer will help.

The original programmer wrote it this way because he thought it was faster. In fact, in PHP 4 it really was faster, especially for large strings.

0
source

Source: https://habr.com/ru/post/1697296/


All Articles