Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of "echo" chunks, while ouputing a file?

What is benefit and difference between the following:

Statement 1:

header("Content-type: image/jpeg");
header('Expires: ' . date('r',time() + 864000));
header("Pragma: public");
header("Cache-Control: public");
header("Content-Length: " . strlen($contents));
$splitString = str_split($contents, 1024);
foreach($splitString as $chunk)
echo $chunk;

Statement 2:

header("Content-type: image/jpeg");
header('Expires: ' . date('r',time() + 864000));
header("Pragma: public");
header("Cache-Control: public");
header("Content-Length: " . strlen($contents));
echo $contents;
like image 719
Chetan Sharma Avatar asked Oct 25 '22 23:10

Chetan Sharma


1 Answers

Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.

If you need to echo a large string, break it into smaller chunks first and then echo each chunk. So, using method 1 to split the string OR using substr to split it and sending to client performs faster for large files than method 2.

like image 178
shamittomar Avatar answered Nov 15 '22 08:11

shamittomar