1

是什么让它fgets()在大文件上变得如此可怕fread

为了演示,运行以下代码:

<?php
$line = str_repeat('HelloWorld', 100000) . "\n";
for($i=0; $i<10000; ++$i)
    file_put_contents('myfile', $line, FILE_APPEND);
//now we have roughly a 1gig file

// We'll even let fread go first incase
// the subsequent test would have any caching benefits
$fp = fopen('myfile2','r');
$start = microtime(true);
while (fread($fp,4096));
$end = microtime(true);
print ($end-$start) . " using fread\n";
fseek($fp, 0);

$start = microtime(true);
while (fgets($fp));
$end = microtime(true);
print ($end-$start) . " using fgets\n";
?>
4

1 回答 1

5

It might have something to do with how you're calling fgets. From the manual, it says that if you leave the second parameter out, then:

If no length is specified, it will keep reading from the stream until it reaches the end of the line.

If the data your working with has some very long lines (eg: "HelloWorld" 100,000 times = 1,000,000 characters), then it has to read that whole thing.

Again, from the manual:

If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

于 2008-10-28T02:36:56.483 回答