Foros del Web » Programando para Internet » PHP »

echo vs. print

Estas en el tema de echo vs. print en el foro de PHP en Foros del Web. Alguien me puede decir que es más adecuado para sacar resultados por pantalla? Y que es mejor con echo/print("..."); o directamente echo/print "...";? Gracias, J....
  #1 (permalink)  
Antiguo 23/10/2004, 03:47
 
Fecha de Ingreso: octubre-2004
Mensajes: 21
Antigüedad: 19 años, 5 meses
Puntos: 0
echo vs. print

Alguien me puede decir que es más adecuado para sacar resultados por pantalla?
Y que es mejor con echo/print("..."); o directamente echo/print "...";?
Gracias,
J.
  #2 (permalink)  
Antiguo 23/10/2004, 04:53
 
Fecha de Ingreso: enero-2004
Mensajes: 235
Antigüedad: 20 años, 3 meses
Puntos: 0
Fragmento extraido de http://phplens.com/lens/php-book/opt...ugging-php.php



Example 1

Here is one simple example that prints an array:

for ($j=0; $j<sizeof($arr); $j++)
echo $arr[$j]."<br>";

This can be substantially speeded up by changing the code to:

for ($j=0, $max = sizeof($arr), $s = ''; $j<$max; $j++)
$s .= $arr[$j]."<br>";

echo $s;

First we need to understand that the expression $j<sizeof($arr) is evaluated within the loop multiple times. As sizeof($arr) is actually a constant (invariant), we move the cache the sizeof($arr) in the $max variable. In technical terms, this is called loop invariant optimization.

The second issue is that in PHP 4, echoing multiple times is slower than storing everything in a string and echoing it in one call. This is because echo is an expensive operation that could involve sending TCP/IP packets to a HTTP client. Of course accumulating the string in $s has some scalability issues as it will use up more memory, so you can see a trade-off is involved here.

An alternate way of speeding the above code would be to use output buffering. This will accumulate the output string internally, and send the output in one shot at the end of the script. This reduces networking overhead substantially at the cost of more memory and an increase in latency. In some of my code consisting entirely of echo statements, performance improvements of 15% have been observed.

ob_start();
for ($j=0, $max = sizeof($arr), $s = ''; $j<$max; $j++)
echo $arr[$j]."<br>";

Note that output buffering with ob_start() can be used as a global optimization for all PHP scripts. In long-running scripts, you will also want to flush the output buffer periodically so that some feedback is sent to the HTTP client. This can be done with ob_end_flush(). This function also turns off output buffering, so you might want to call ob_start() again immediately after the flush.

In summary, this example has shown us how to optimize loop invariants and how to use output buffering to speed up our code.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 20:46.