note 117050 added to function.fgets

From: Date: Wed, 08 Apr 2015 03:03:57 +0000
Subject: note 117050 added to function.fgets
Groups: php.notes 
Request: Send a blank email to php-notes+get-202200@lists.php.net to get a copy of this message
A better example, to illustrate the differences in speed for large files, between fgets and stream_get_line. This example simulates situations where you are reading potentially very long lines, of an uncertain length (but with a maximum buffer size), from an input source. As Dade pointed out, the previous example I provided was much to easy to pick apart, and did not adequately highlight the issue I was trying to address. Note that specifying a definitive end-character for fgets (ie: newline), generally decreases the speed difference reasonably significantly. #!/usr/bin/php <?php $plaintext=file_get_contents('http://loripsum.net/api/60/verylong/plaintext'); # Should be around 90k characters $plaintext=str_replace("\n"," ",$plaintext); # Get rid of newlines $fp=fopen("/tmp/SourceFile.txt","w"); for($i=0;$i<100000;$i++) { fputs($fp,substr($plaintext,0,rand(4096,65534)) . "\n"); } fclose($fp); $fp=fopen("/tmp/SourceFile.txt","r"); $start=microtime(true); while($line=fgets($fp,65535)) { 1; } $end=microtime(true); fclose($fp); $delta1=($end - $start); $fp=fopen("/tmp/SourceFile.txt","r"); $start=microtime(true); while($line=stream_get_line($fp,65535)) { 1; } $end=microtime(true); fclose($fp); $delta2=($end - $start); $pdiff=$delta1/$delta2; print "stream_get_line is " . ($pdiff>1?"faster":"slower") . " than fgets - pdiff is $pdiff\n"; ?> $ ./testcase.php stream_get_line is faster than fgets - pdiff is 1.760398041785 Note that, in a vast majority of situations in which php is employed, tiny differences in speed between system calls are of negligible importance. ---- Server IP: 72.52.91.14 Probable Submitter: 118.208.163.12 ---- Manual Page -- http://php.net/manual/en/function.fgets.php Edit -- https://master.php.net/note/edit/117050 Del: integrated -- https://master.php.net/note/delete/117050/integrated Del: useless -- https://master.php.net/note/delete/117050/useless Del: bad code -- https://master.php.net/note/delete/117050/bad+code Del: spam -- https://master.php.net/note/delete/117050/spam Del: non-english -- https://master.php.net/note/delete/117050/non-english Del: in docs -- https://master.php.net/note/delete/117050/in+docs Del: other reasons-- https://master.php.net/note/delete/117050 Reject -- https://master.php.net/note/reject/117050 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#202200) next »