是PHP';s file_get_contents提高了内存和数据效率


is PHP's file_get_contents memory and data efficient?

我正在制作一个推送通知服务器,从外部(第三方)html页面收集特定数据,如果我知道我需要的信息在第一个字符内,例如5000个字符,如果我声明MAX_LENGTH,PHP真的会用更少的内存吗?还是整个页面都已加载到内存中?此外,是下载了整个html页面,还是在达到限制后连接中断?(进而节省数据传输成本)

$html = file_get_contents ("http://.....", false, null, -1, 5000);

谢谢。

是的,它确实节省了内存和带宽。。。我还进行了一个速度测试(这与这个问题并不完全相关,但很有用,并表明它确实停止了读取流)和一个内存测试来演示。我没有运行峰值内存测试,但至少您的$html变量将在那里存储更少的信息并节省内存。

Time to get ALL characters of remote page 10 times: 6.0368211269379
Time to get ALL characters of remote page 10 times: 6.0158920288086
Time to get ALL characters of remote page 10 times: 5.8945140838623
Time to get ALL characters of remote page 10 times: 8.867082118988
Time to get ALL characters of remote page 10 times: 5.7686760425568
Time to get first ten characters of page 10 times: 4.2118229866028
Time to get first ten characters of page 10 times: 4.5816869735718
Time to get first ten characters of page 10 times: 4.2146580219269
Time to get first ten characters of page 10 times: 4.1949119567871
Time to get first ten characters of page 10 times: 4.1788749694824

Memory Useage First 10 characters:40048
Memory Useage ALL characters:101064

从这里开始,一直到这里,最后到_php_stream_copy_to_mem函数,看起来file_get_contents()函数在流达到请求的最大长度后实际上会停止读取流。

是的,因为它在引擎盖下使用流函数,当它达到极限时,它实际上会停止。文件页面上也写着

"file_get_contents()是将文件内容读取为字符串的首选方法。如果操作系统支持,它将使用内存映射技术来提高性能。"

所以它实际上应该能给你带来你想要的提升。