【问题标题】:is PHP's file_get_contents memory and data efficient?PHP 的 file_get_contents 内存和数据效率高吗?
【发布时间】:2025-12-31 04:15:11
【问题描述】:
我正在制作一个推送通知服务器,它从外部(第三方)html 页面收集特定数据,如果我知道我需要的信息在第一个例如5000 个字符,如果我声明 MAX_LENGTH,PHP 实际上会使用更少的内存吗?还是整个页面都完全加载到内存中?此外,是否下载了整个 html 页面,或者一旦达到限制,连接是否断开? (进而节省数据传输成本)
$html = file_get_contents ("http://.....", false, null, -1, 5000);
谢谢。
【问题讨论】:
标签:
php
file-get-contents
vps
【解决方案1】:
是的,它确实节省了内存和带宽...我还进行了速度测试(这与这个问题并不完全相关,但很有用,并表明它确实停止读取流)和内存测试只是为了演示.我没有运行峰值内存测试,但至少您的 $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
【解决方案3】:
是的,因为它在底层使用流函数,当它达到限制时它实际上会停止。同样在文档页面上它说
“file_get_contents() 是将文件内容读入字符串的首选方法。如果您的操作系统支持,它将使用内存映射技术来提高性能。”
因此它实际上应该为您提供所需的提升。