PHP 的 file_get_contents 内存和数据效率高吗?
我正在制作一个推送通知服务器,它从外部(第三方)html 页面收集特定数据,如果我知道我需要的信息在前 5000 个字符内,如果我声明 MAX_LENGTH,PHP 实际上会使用更少的内存吗?或者整个页面是否完全加载到内存中?另外,是否会下载整个 html 页面,或者一旦达到限制,连接是否会中断? (进而节省数据传输成本)
$html = file_get_contents ("http://.....", false, null, -1, 5000);
谢谢。
I'm making a push notification server that gathers specific data from an external (third-party) html page, if I know the information I need is within the first e.g. 5000 characters, will PHP actually use less memory if I state a MAX_LENGTH? Or is the whole page loaded entirely into memory anyway? Additionally, is the entire html page downloaded or is the connection broken once the limit is hit? (and in turn saving data transfer costs)
$html = file_get_contents ("http://.....", false, null, -1, 5000);
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它确实节省了内存和带宽...我还进行了速度测试(这与这个问题并不完全相关,但很有用,并且表明它确实停止读取流)和内存测试只是为了演示。我没有运行峰值内存测试,但至少你的 $html 变量将存储更少的信息并节省内存。
Yes, it does save memory and bandwidth... I also ran a speed test (which is not completely germane to this question, but is useful and suggests that it does stop reading the stream) and a memory test just to demonstrate. I did not run a peak memory test, but at the very least your $html variable will store less information and save memory there.
从此处开始挖掘源代码,如下这里,最后到达_php_stream_copy_to_mem 函数,它看起来像
file_get_contents()一旦流达到请求的最大长度,
函数实际上将停止读取流。Digging through the source starting here, following to here, and finally ending up at the _php_stream_copy_to_mem function, it looks like the
file_get_contents()
function will actually stop reading the stream once it reaches the requested max length.是的,因为它在底层使用流函数,所以当它达到限制时它实际上会停止。另外,在文档页面上,它还说
“file_get_contents() 是将文件内容读入字符串的首选方法。如果您的操作系统支持,它将使用内存映射技术来提高性能。”
所以它实际上应该给你带来你想要的提升。
Yes because it uses stream functions under the hood, it will actually stop when it reaches the limit. Also on the documentation page it says
"file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance."
so it should actually give you the boosts you look for.