什么更快? file_put_contents(); fopen(); fwrite(); fclose();?
什么更好?我有自己的 MySQL 日志,大约有 90MB,但我不确定应该使用哪一个。每当有查询要执行时它都会打开文件。
什么更快?
What is better? I have my own MySQL log so it has about 90MB, but I'm not sure which one should I use. It opens file EVERYTIME there is query to execute.
What's faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据 本文,
fwrite()
速度稍快一些。 (链接到 Wayback Machine,因为站点不再存在。)我的猜测是
file_put_contents()
无论如何只是这三个方法的包装器,因此您将失去开销。编辑:此网站有相同的信息。
According to this article, the
fwrite()
is a smidgen faster. (Link to Wayback Machine, because site no longer exists.)My guess is that
file_put_contents()
is just a wrapper around those three methods anyways, so you would lose the overhead.EDIT : This site has the same information.
该函数与依次调用 fopen()、fwrite() 和 fclose() 将数据写入文件相同。
检查文档:
http://php.net/manual/en/function.file-put -contents.php
肖恩
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
Check the docs:
http://php.net/manual/en/function.file-put-contents.php
Shaun
取决于您的用例。我打开了超过 0.5 GB 的文件,我当然不想使用 file() 或 file_get_contents(); file_put_contents 无法工作,因为我也需要读取该文件。
如果您真的只是对附加文件而不阅读感兴趣,那么这并不重要;如果您尝试将整个文件读入内存(或从内存中写入整个文件),它同样并不重要 - 正如我所看到的,速度增益是舍入误差。
但是,如果您期望这些文件会变得庞大,或者您只需要给定文件行数的一小部分,我不建议使用 fopen (或
SplFileObject,太棒了)足够强大——用这些代码从文件中间读取真的很容易。
另一方面,由于您只是进行日志记录,因此我个人认为简单地将 file_put_contents 与附加标志一起使用会更清晰、更简洁。它让每个人都知道发生了什么,而无需再看一遍。
Depends on your use-case. I've opened files which were over .5 GB, and I certainly didn't want to use file() or file_get_contents(); And file_put_contents couldn't work because I needed to read the file too.
If you're really just interested in appending a file without reading, it doesn't terribly matter; if you're trying to read a whole file into memory (or write a whole file from memory), it similarly does not really matter -- the speed gain, as near as I've seen, is round-off error.
BUT, if you're expecting that these files will ever grow to gargantuan beasts, or if you only need a small subset of the number of lines of a given file, I cannot suggest use of fopen (or the
SplFileObject
, which is AWESOME) strongly enough -- it is really easy to read from the middle of a file with these.Since you're just logging, on the other hand, I, personally, find it clearer and more concise to simply use file_put_contents with the append flag. It lets everyone know what's going on without having to look twice.
像往常一样,你对它进行了基准测试吗?无论如何,file_put_contents 本质上只是 3 个
f*()
调用的包装器,因此最多您会因执行一次额外的函数调用而遭受损失,但会因需要解析的前端代码更少而获得一些好处。As per usual, have you benchmarked it? file_put_contents is essentially just a wrapper around the 3
f*()
calls anyways, so at most you're losing out by doing one extra function call, but gaining somewhat by having less front-end code to parse.