什么是PHP的fgets()使它在大文件上如此可怕?

What is it about fgets() implementation that makes it so horrible on large files vs fread?

To demonstrate, run this code:

<?php
$line = str_repeat('HelloWorld', 100000) . "
";
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
";
fseek($fp, 0);

$start = microtime(true);
while (fgets($fp));
$end = microtime(true);
print ($end-$start) . " using fgets
";
?>
dongpan8439
dongpan8439 这太可怕了吗?你能给出一些具有这种性能影响的代码示例吗?
接近 12 年之前 回复

1个回答



这可能与你如何调用 fgets </ code>有关。 从手册中可以看出,如果你把第二个参数输出,那么:</ p>


如果没有指定长度,它将继续从流中读取,直到它到达 队伍的尽头。 </ p>
</ blockquote>

如果您使用的数据有很长的行(例如:“HelloWorld”100,000次= 1,000,000个字符),那么它必须读取整个内容。 </ p>

再次,从手册:</ p>


如果文件中的大多数行都大于8KB,则为 为脚本指定最大行长度的资源效率更高。 </ p>
</ blockquote>
</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐