Chetan Sharma
Chetan Sharma

Reputation: 2557

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;

Upvotes: 5

Views: 392

Answers (4)

alex
alex

Reputation: 490597

If the $contents is very large, you can echo it in chunks to stop the whole thing being echo'd at once.

Upvotes: 0

shamittomar
shamittomar

Reputation: 46702

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.

Upvotes: 3

pooja
pooja

Reputation: 2432

in the first statement content divide into 1024 bytes chunks and one chunk have 1024 bytes content and in the second statement detemine the length of whole content ant then echo this but in first divide in chunk and then echo with help of for each one by one.

Upvotes: 0

sbeam
sbeam

Reputation: 4892

Statement 1 adds unnecessary overhead and obfuscation.

Upvotes: 0

Related Questions