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.
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.
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
Check the docs:
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.
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.
- If there is only one write-operation for one file in a request, file_put_contents is better than fwrite, because it has wrappered open, write and close functions, and as fast as fwrite.
- If there are multi-write for one file in a request, we need open file first, then write multi-times, so fwrite is faster. But, if it is a very busy system, which has a lot of “open files”(ulimit -a | grep “open files”), file_put_contents will be a more reasonable choose, because it keep the file handler shorter than fwrite.